java读取文本文件的方法有很多,这个例子主要介绍最简单,最常用的BufferedReader类。
完整例子如下:
- package net.chinaunix.blog.hzm.text;
-
-
import java.io.BufferedReader;
-
import java.io.FileReader;
-
import java.io.IOException;
-
-
public class ReadFile {
-
-
private String path;
-
-
-
public ReadFile(String filePath){
-
path = filePath;
-
}
-
-
public String[] openFile() throws IOException{
-
-
FileReader fr = new FileReader(path);
-
BufferedReader textReader = new BufferedReader(fr);
-
-
String[] textData = new String[readLines()];
-
int i;
-
for(i=0; i < readLines();i++){
-
textData[i] = textReader.readLine();
-
}
-
-
textReader.close();
-
-
return textData;
-
}
-
-
int readLines() throws IOException{
-
FileReader fileToRead = new FileReader(path);
-
BufferedReader bf = new BufferedReader(fileToRead);
-
-
int numberOfLines = 0;
-
-
@SuppressWarnings("unused")
-
String oneLine;
-
while((oneLine = bf.readLine()) != null){
-
numberOfLines++;
-
}
-
bf.close();
-
-
return numberOfLines;
-
-
}
-
}
- package net.chinaunix.blog.hzm.text;
-
-
import java.io.IOException;
-
-
public class FileData {
-
-
public static void main(String[] args) throws IOException{
-
-
String filePath = "C:/text.txt";
-
-
try{
-
ReadFile reader = new ReadFile(filePath);
-
String[] content = reader.openFile();
-
-
int i;
-
for(i=0;i<content.length;i++){
-
System.out.println(content[i]);
-
}
-
-
}catch(IOException e){
-
System.out.println("异常信息:" + e.getMessage());
-
}
-
}
-
}
java.io.BufferedReader
The buffer size may be specified, or the default size may be used. The
default is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding read
request to be made of the underlying character or byte stream. It is therefore
advisable to wrap a BufferedReader around any Reader whose read() operations may
be costly, such as FileReaders and InputStreamReaders. For example,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file.
Without buffering, each
invocation of read() or readLine() could cause bytes to be read from the file,
converted into characters, and then returned, which can be
very inefficient.
Programs that use DataInputStreams for textual input can be localized by
replacing each DataInputStream with an appropriate BufferedReader.
java.io.FileReader
FileReader is meant for reading streams of characters. For
reading streams of raw bytes, consider using a FileInputStream.
参考:
阅读(2343) | 评论(0) | 转发(0) |