Read a text file in JAVA

Text file can be directly read using FileReader & BufferedReader classes. In several technote, it is mentioned to get the text file as a input stream, then convert to Inputstreamreader and then BufferedReader.

Any reasons why we need to use InputStream approach

Upvotes: 2

Views: 129

Answers (2)

Adil Shaikh
Adil Shaikh

Reputation: 44740

FileReader is convenience class for reading character files. 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.

Upvotes: 7

fge
fge

Reputation: 121820

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. That's the first point.

Second, and more importantly:

  • Use JSR 203. Don't use File anymore.
  • Use try-with-resources.

Both of them appeared in Java 7. So, the new way to read a text file is as such:

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; this will read in UTF-8 by default. Also in Java 8, you have Files.lines():

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

And yes, use try-with-resources for such a stream!

Upvotes: 0

Related Questions