Reputation: 289
I am going over java.io
and some aspects are confusing to me:
Is there any perfomance difference between FileReader
and InputStreamReader
?
Reader fileReader = new FileReader("input.txt");
Reader fileReader2 = new InputStreamReader(new FileInputStream("input.txt"));
Which one is preferable over another one ?
Upvotes: 0
Views: 80
Reputation: 1503489
I wouldn't focus on the performance. I'd focus on the massive correctness difference between them: FileReader
always uses the platform-default encoding, which is almost never a good idea.
I believe that's actually slightly more efficient (at least in some cases) than specify a Charset
in the InputStreamReader
constructor, even if you pass in the platform-default Charset
, but I would still do the latter for clarity and correctness.
Of course, these days I'd probably go straight to Files.newBufferedReader
as a simpler approach that a) let's me specify the Charset
; b) defaults to UTF-8 which is what I normally want anyway; c) creates a BufferedReader
which is also what I often want, mostly for the sake of readLine()
.
Upvotes: 3
Reputation: 100309
There's no difference. You can understand this looking into the source code:
public class FileReader extends InputStreamReader {
// ...
public FileReader(String fileName) throws FileNotFoundException {
super(new FileInputStream(fileName));
}
// ...
}
So this is merely a syntactic sugar. FileReader
extends InputStreamReader
, but has no additional changes except constructors.
Also note that FileReader
uses system default file encoding and there's no way to specify the custom encoding with it. This I'd recommend not to use it at all. In modern Java 1.7+ NIO there are new preferred methods:
java.nio.file.Files.newBufferedReader(Path)
: new UTF-8 BufferedReader
java.nio.file.Files.newBufferedReader(Path, Charset)
: new BufferedReader
with specified Charset
.
Upvotes: 2