在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
当前回答
ASCII是一个文本文件,因此您可以使用reader进行读取。Java还支持使用InputStreams从二进制文件中读取。如果要读取的文件很大,那么您可能希望在FileReader之上使用BufferedReader来提高读取性能。
阅读这篇关于如何使用Reader的文章
我还推荐你下载并阅读这本很棒(但免费)的书,叫做《用Java思考》
在Java 7中:
new String(Files.readAllBytes(...))
(文档) 或
Files.readAllLines(...)
(文档)
在Java 8中:
Files.lines(..).forEach(...)
(文档)
其他回答
org.apache.commons.io.FileUtils中的方法也可能非常方便,例如:
/**
* Reads the contents of a file line by line to a List
* of Strings using the default encoding for the VM.
*/
static List readLines(File file)
如果您有一个大文件,您可以使用Apache Commons IO迭代处理该文件,而不会耗尽可用内存。
try (LineIterator it = FileUtils.lineIterator(theFile, "UTF-8")) {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
}
ASCII是一个文本文件,因此您可以使用reader进行读取。Java还支持使用InputStreams从二进制文件中读取。如果要读取的文件很大,那么您可能希望在FileReader之上使用BufferedReader来提高读取性能。
阅读这篇关于如何使用Reader的文章
我还推荐你下载并阅读这本很棒(但免费)的书,叫做《用Java思考》
在Java 7中:
new String(Files.readAllBytes(...))
(文档) 或
Files.readAllLines(...)
(文档)
在Java 8中:
Files.lines(..).forEach(...)
(文档)
你想怎么处理这篇文章?文件是否小到可以装入内存?我会尽量找到最简单的方法来处理您需要的文件。FileUtils库可以很好地处理这个问题。
for(String line: FileUtils.readLines("my-text-file"))
System.out.println(line);
我编写的这段代码对于非常大的文件要快得多:
public String readDoc(File f) {
String text = "";
int read, N = 1024 * 1024;
char[] buffer = new char[N];
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while(true) {
read = br.read(buffer, 0, N);
text += new String(buffer, 0, read);
if(read < N) {
break;
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
return text;
}