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.
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.
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.
InputStream − This is used to read (sequential) data from a source. OutputStream − This is used to write data to a destination.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With