Choosing between FileReader and InputStreamReader

Basimalla Sebastin picture Basimalla Sebastin · Mar 30, 2012 · Viewed 17.6k times · Source

I have two methods to read Text File In java one using FileReader and Other File InputStream

FileReader fr=new FileReader("C:\\testq\\test.txt");
BufferedReader br=new BufferedReader(fr);
String s;
while((s=br.readLine())!=null){
    System.out.println("value are "+s);
}

and Other is

FileInputStream fstream = new FileInputStream("C:\\testnew\\out.text");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null){
   System.out.println (strLine);
}

Though both give me output ...I just want to know which is the best way to do it.

Answer

Jon Skeet picture Jon Skeet · Mar 30, 2012

I would strongly advise using InputStreamReader instead of FileReader, but explicitly specifying the character encoding. That's really the biggest benefit of using InputStreamReader (and the lack of ability to specify an encoding for FileReader is a major hole in the API, IMO).

I'd also remove the "layer" using DataInputStream - just pass the FileInputStream to the InputStreamReader constructor.

Before Java 8

Alternatively, consider using some of the many convenience methods in Guava which can make this sort of thing much simpler. For example:

File file = new File("C:\\testnew\\out.text");
List<String> lines = Files.readLines(file, Charsets.UTF_8));

From Java 8

Java 8 introduced a bunch of new classes and methods in java.nio.files, many of which default (sensibly) to UTF-8:

Path path = Paths.get("C:\\testnew\\out.text");
List<String> lines = Files.readAllLines(path);