3

What's the best way to read a line from a file using the New I/O ?

I can only get a byte at a time.

Any idea?

Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
Rafael Orágio
  • 1,718
  • 5
  • 19
  • 26

3 Answers3

4

Or for small files you can do this:

List<String> smallFilesLines =  Files.readAllLines(  
FileSystems.getDefault().getPath("smallFile.txt"), StandardCharsets.UTF_8);  

for (String oneLine : smallFilesLines) {
   System.out.println(oneLine); 
}
damon
  • 41
  • 1
2

BufferedReader's readline() method should be enough. Otherwise you have to read an arbitrary number of bytes and parse for the endline '\n' or \r\n' if it is in windows style line ending

LordDoskias
  • 3,121
  • 3
  • 30
  • 44
2

Are you referring to the NIO introduced in Java 5.0, 7 years ago? Or the Asynchronous NIO adding in Java 7?

In short the simple answer is that using BufferedReader is much, much simpler and not much slower.

If you must use ByteBuffer, or you want that last bit of performance, you have to read one byte at a time. (And you have handle the situation that only part of the line has been read so you can run out of data in the ByteBuffer before you reach the new line)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Interesting your answer. I had doubts about the performance of the "BufferedReader". In this case I will not need to parse. – Rafael Orágio Nov 07 '11 at 12:01
  • 1
    If you have to read text from a file, you can get within 25% of the maximum performance you might get with NIO (without the complexity) In any case you are more likely to be limited by your hardware if you have a HDD. (With SSD it can make a small difference) – Peter Lawrey Nov 07 '11 at 13:22