Read line using Java New I/O

2020-04-11 05:25发布

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?

标签: java file line nio
3条回答
家丑人穷心不美
2楼-- · 2020-04-11 06:08

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)

查看更多
再贱就再见
3楼-- · 2020-04-11 06:10

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); 
}
查看更多
Explosion°爆炸
4楼-- · 2020-04-11 06:14

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

查看更多
登录 后发表回答