在Java中,似乎有不同的方式来读取和写入文件数据。

我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?


当前回答

如果您有一个大文件,您可以使用Apache Commons IO迭代处理该文件,而不会耗尽可用内存。

try (LineIterator it = FileUtils.lineIterator(theFile, "UTF-8")) {
    while (it.hasNext()) {
        String line = it.nextLine();
        // do something with line
    }
}

其他回答

最简单的方法是使用Java中的Scanner类和FileReader对象。简单的例子:

Scanner in = new Scanner(new FileReader("filename.txt"));

扫描器有几个方法读取字符串,数字,等…您可以在Java文档页面上查找有关这方面的更多信息。

例如,将整个内容读入String:

StringBuilder sb = new StringBuilder();
while(in.hasNext()) {
    sb.append(in.next());
}
in.close();
outString = sb.toString();

另外,如果你需要一个特定的编码,你可以使用这个来代替FileReader:

new InputStreamReader(new FileInputStream(fileUtf8), StandardCharsets.UTF_8)

ASCII是一个文本文件,因此您可以使用reader进行读取。Java还支持使用InputStreams从二进制文件中读取。如果要读取的文件很大,那么您可能希望在FileReader之上使用BufferedReader来提高读取性能。

阅读这篇关于如何使用Reader的文章

我还推荐你下载并阅读这本很棒(但免费)的书,叫做《用Java思考》

在Java 7中:

new String(Files.readAllBytes(...))

(文档) 或

Files.readAllLines(...)

(文档)

在Java 8中:

Files.lines(..).forEach(...)

(文档)

在实践中,缓冲流类的性能要高得多,以至于NIO.2 API包含了专门返回这些流类的方法,部分原因是为了鼓励您始终在应用程序中使用缓冲流。

这里有一个例子:

Path path = Paths.get("/myfolder/myfile.ext");
try (BufferedReader reader = Files.newBufferedReader(path)) {
    // Read from the stream
    String currentLine = null;
    while ((currentLine = reader.readLine()) != null)
        //do your code here
} catch (IOException e) {
    // Handle file I/O exception...
}

您可以替换此代码

BufferedReader reader = Files.newBufferedReader(path);

BufferedReader br = new BufferedReader(new FileReader("/myfolder/myfile.ext"));

我推荐这篇文章来学习Java NIO和IO的主要用途。

这里有一个简单的解决方案:

String content = new String(Files.readAllBytes(Paths.get("sample.txt")));

或读作列表:

List<String> content = Files.readAllLines(Paths.get("sample.txt"))

可能没有缓冲I/O那么快,但是非常简洁:

    String content;
    try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
        content = scanner.next();
    }

\Z模式告诉扫描器分隔符是EOF。