我有一个生成 ByteArrayOutputStream
的方法,我想使用 FileChannel
将这些内容放入一个文件中。使用 FileOutputStream
,我可以这样做:
ByteArrayOutputStream baos = MyClass.myMethod(); // get my stream
FileOutputStream out = new FileOutputStream("somefile"); // I want to write to "somefile"
out.writeTo(baos); // write
如何使用 FileChannel
执行此操作?我知道我可以将 baos
转换为字节数组,然后将其转换为 ByteBuffer
,最后我可以使用 FileChannel.write()
写东西。但这意味着将流的内容转储到内存中,而且内存相当大。
除非我弄错了,将 ByteArrayOutputStream
转换为某种类型的 InputStream
,然后使用 Channels.newChannel(InputStream in)
, 最后使用 FileChannel.transferFrom()
会遇到同样的问题。
最佳答案
您可以从另一端尝试:不是将 ByteArrayOutputStream
包装到一个 channel 中,您可以将您的 FileChannel
包装到 OutputStream
中,并且通过调用 out.writeTo
完成写入:
ByteArrayOutputStream baos = MyClass.myMethod1();
FileChannel channel = MyClass.myMethod2();
OutputStream out = Channels.newOutputStream(channel);
out.writeTo(baos);
关于java - 使用 NIO FileChannel 将 ByteArrayOutputStream 的内容写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30812115/