简体   繁体   English

在JAVA中读取文本文件

[英]Read a text file in JAVA

Text file can be directly read using FileReader & BufferedReader classes. 可以使用FileReader和BufferedReader类直接读取文本文件。 In several technote, it is mentioned to get the text file as a input stream, then convert to Inputstreamreader and then BufferedReader. 在几个技术说明中,提到将文本文件作为输入流,然后转换为Inputstreamreader,然后转换为BufferedReader。

Any reasons why we need to use InputStream approach 我们需要使用InputStream方法的任何原因

FileReader is convenience class for reading character files. FileReader是读取字符文件的便捷类。 The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. 此类的构造函数假定默认字符编码和默认字节缓冲区大小是适当的。 To specify these values yourself, construct an InputStreamReader on a FileInputStream. 要自己指定这些值,请在FileInputStream上构造一个InputStreamReader。

Complement to this answer ... 补充这个答案 ......

There really isn't a need to use a BufferedReader if you don't need to, except that it has the very convenient .readLine() method. 如果你不需要,确实不需要使用BufferedReader ,除了它有非常方便的.readLine()方法。 That's the first point. 这是第一点。

Second, and more importantly: 其次,更重要的是:

  • Use JSR 203. Don't use File anymore. 使用JSR 203.不要再使用File了。
  • Use try-with-resources. 使用try-with-resources。

Both of them appeared in Java 7. So, the new way to read a text file is as such: 它们都出现在Java 7中。因此,读取文本文件的新方法是这样的:

final Path path = Paths.get("path/to/the/file");

try (
    final BufferedReader reader = Files.newBufferedReader(path,
        StandardCharsets.UTF_8);
) {
    // use reader here
}

In Java 8, you also have a version of Files.newBufferedReader() which does not take a charset as an argument; 在Java 8中,您还有一个Files.newBufferedReader()版本,它将charset作为参数; this will read in UTF-8 by default. 这将默认以UTF-8读取。 Also in Java 8, you have Files.lines() : 同样在Java 8中,您有Files.lines()

try (
    final Stream<String> stream = Files.lines(thePath);
) {
    // use the stream here
}

And yes, use try-with-resources for such a stream! 是的,对这样的流使用try-with-resources!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM