[英]Read text file to list of Strings using NIO FileChannel
I'm trying to read an entire text file into list of strings using the non-blocking FileChannel. 我正在尝试使用非阻塞FileChannel将整个文本文件读入字符串列表。 Using regular IO it's as simple as:
使用常规IO就像这样简单:
List<String> lines = null;
try {
lines = Files.readAllLines(FILE);
} catch (IOException ioe) {
ioe.printStackTrace();
}
My attempt using NIO and FileChannel looks something like this: 我尝试使用NIO和FileChannel看起来像这样:
List<String> words = null;
try {
FileInputStream stream = new FileInputStream(FILE);
FileChannel channel = stream.getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int) channel.size());
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
for (String line = reader.readLine(); line != null; line = reader.readLine())
words.add(line);
reader.close();
buffer.clear();
channel.close();
stream.close();
for (String word : words)
System.out.println(word);
} catch (IOException ioe) {
ioe.printStackTrace();
}
I map the entire file to a ByteBuffer, read the ByteBuffer into a byte array, then try to read the byte array using a BufferedReader, but when I try to print the contents of the List i get a NullPointerException. 我将整个文件映射到ByteBuffer,将ByteBuffer读入字节数组,然后尝试使用BufferedReader读取字节数组,但是当我尝试打印List的内容时,我得到了NullPointerException。
What is the proper way to go about doing this? 这样做的正确方法是什么?
Besides @Slaw 's point that this code is not using non-blocking IO, JavaDoc for FileChannel.map states: 除了@Slaw指出此代码未使用非阻塞IO之外,用于FileChannel.map的JavaDoc还指出:
The mapped byte buffer returned by this method will have a position of zero and a limit and capacity of size;
此方法返回的映射的字节缓冲区的位置为零,大小的限制和容量; its mark will be undefined.
其标记将是不确定的。
After commenting the flip operation and initializing the words list, the code worked as I expected. 在注释了翻页操作并初始化了单词列表之后,代码按预期工作了。
public static void main(String[] args) {
List<String> words = new ArrayList<>();
File FILE = new File("SOME_FILE_OF_LINES");
try {
FileInputStream stream = new FileInputStream(FILE);
FileChannel channel = stream.getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int) channel.size());
// buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
for (String line = reader.readLine(); line != null; line = reader.readLine())
words.add(line);
reader.close();
buffer.clear();
channel.close();
stream.close();
for (String word : words)
System.out.println(word);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.