Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing between FileReader and InputStreamReader

Tags:

java

java-io

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.

like image 262
Basimalla Sebastin Avatar asked Mar 30 '12 07:03

Basimalla Sebastin


People also ask

What is the difference between FileReader and InputStreamReader in java?

FileInputStream is Byte Based, it can be used to read bytes. FileReader is Character Based, it can be used to read characters. FileInputStream is used for reading binary files. FileReader is used for reading text files in platform default encoding.

Is FileReader deprecated?

This node has been deprecated and its use is not recommended. Please search for updated nodes instead. This node can be used to read data from an ASCII file or URL location.

What is difference between FileInputStream and Fileoutputstream?

InputStream − This is used to read (sequential) data from a source. OutputStream − This is used to write data to a destination.


1 Answers

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);
like image 176
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet