[英]How to write a reader into a file using nio?
Given a Reader, a Charset, and a Path, how do I correctly and efficiently write the reader's content into a file?给定一个阅读器、一个字符集和一个路径,我如何正确有效地将阅读器的内容写入文件?
The total size of the reader's content is not known in advance.读者内容的总大小事先不知道。
This is my current solution:这是我目前的解决方案:
CharBuffer charBuffer = CharBuffer.allocate(1024);
try (FileChannel fc = (FileChannel) Files.newByteChannel(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) {
while (true) {
int size = reader.read(charBuffer);
if (size < 0) break;
charBuffer.flip();
ByteBuffer bytes = charset.encode(charBuffer);
fc.write(bytes);
charBuffer.flip();
}
}
It works but it allocates a new ByteBuffer in every loop.它可以工作,但它在每个循环中分配一个新的 ByteBuffer。 I could try to reuse the byte buffer, but I would actually prefer a solution that uses only one buffer in total.
我可以尝试重用字节缓冲区,但实际上我更喜欢总共只使用一个缓冲区的解决方案。
Using ByteBuffer#toCharBuffer
is not an option because it does not consider the charset.使用
ByteBuffer#toCharBuffer
不是一个选项,因为它不考虑字符集。
I also don't like the type cast in the try-statement, is there a cleaner solution?我也不喜欢 try 语句中的类型转换,有更清洁的解决方案吗?
The simplest way to transfer reader to a path is to use the built in methods of Files
:将 reader 传输到路径的最简单方法是使用
Files
的内置方法:
try(var out = Files.newBufferedWriter(path, charset, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) {
reader.transferTo(out);
}
This does not need the CharBuffer and simplifies the logic of the code you need to write for this often needed task.这不需要 CharBuffer 并简化了您需要为这个经常需要的任务编写的代码的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.