在FileReader和InputStreamReader之间进行选择 [英] Choosing between FileReader and InputStreamReader
问题描述
我有两种方法来读取文本文件在java中使用FileReader和其他文件InputStream
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);
}
和其他是
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.
推荐答案
我强烈建议使用 InputStreamReader
而不是 FileReader
,但明确指定了字符编码。这真的是使用 InputStreamReader
的最大好处(并且缺乏为 FileReader
指定编码的能力是一个主要漏洞在API,IMO)。
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).
我还使用 DataInputStream
删除图层 - 只需通过 FileInputStream
到 InputStreamReader
构造函数。
I'd also remove the "layer" using DataInputStream
- just pass the FileInputStream
to the InputStreamReader
constructor.
在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));
来自Java 8
Java 8在 java.nio.files
中引入了一堆新的类和方法,其中许多默认(明智地)为UTF-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);
这篇关于在FileReader和InputStreamReader之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!