Your question asks about data extraction, but the code actually just prints the file to System.out
with possible Carriage return/Newline translation. Frankly, you haven't asked a very good question (it doesn't do what you claim, and it lacks specific details about how poor your performance is or how you measured it), but there is some code to be reviewed anyway.
Your exception handling is wrong. What happens if new FileReader(…)
throws an exception?
There is some hidden work being done that you may not be aware of.
- As I alluded to above,
BufferedReader.readLine()
accepts either Carriage return, Newline, or some combination of the two as a line termination marker. Then, System.out.println()
will print each line, using the Java default line termination character. If you don't need this normalization of the line termination, don't call .readLine()
. Just repeatedly read to a char[]
buffer and write it out. Then you also wouldn't be creating a String
for each line.
FileReader
might also be doing some extraneous work. It creates an InputStreamReader
that translates bytes into chars using the system default character encoding. Assuming you don't care about such transcoding, you could work with byte[]
arrays instead.
- If you just want to funnel data from a source to a sink as efficiently as possible,
java.nio.file.Files.copy()
is probably your best bet.
That said, the code you wrote is pretty standard and is fast enough for most purposes, and you usually don't need to resort to the hacks I mentioned above. If you're seeing a performance problem, it's probably because your System.out
is attached to your console, and console output is slow. (Sometimes surprisingly so!) Try redirecting your System.out
to /dev/null
or NUL:
to measure your input and output bottlenecks separately.
cat
and on Windowstype
which do exactly the same thing. \$\endgroup\$ – ChrisWue Mar 4 '14 at 6:46