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 ?
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()
.
See more on this question at Stackoverflow