简体   繁体   English

使用Java New I / O读取行

[英]Read line using Java New I/O

What's the best way to read a line from a file using the New I/O ? 使用New I / O从文件中读取行的最佳方法是什么?

I can only get a byte at a time. 我一次只能得到一个字节。

Any idea? 任何的想法?

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); 
}

BufferedReader 's readline() method should be enough. BufferedReader的readline()方法应该足够了。 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 否则你必须读取任意数量的字节并解析结束'\\ n'或\\ r \\ n'如果它在窗口样式行结束

Are you referring to the NIO introduced in Java 5.0, 7 years ago? 您是指7年前在Java 5.0中引入的NIO吗? Or the Asynchronous NIO adding in Java 7? 或者在Java 7中添加异步NIO?

In short the simple answer is that using BufferedReader is much, much simpler and not much slower. 简而言之,简单的答案是使用BufferedReader更简单,更慢。

If you must use ByteBuffer, or you want that last bit of performance, you have to read one byte at a time. 如果必须使用ByteBuffer,或者想要最后一点性能,则必须一次读取一个字节。 (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) (并且您已经处理了只读取了部分行的情况,因此在到达新行之前,您可能会耗尽ByteBuffer中的数据)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM