Java 使用NIO FileChannel将ByteArrayOutputStream的内容写入文件
我有一个方法可以通过tearrayoutputstream生成Java 使用NIO FileChannel将ByteArrayOutputStream的内容写入文件,java,nio,filechannel,bytearrayoutputstream,Java,Nio,Filechannel,Bytearrayoutputstream,我有一个方法可以通过tearrayoutputstream生成,我想使用FileChannel将这些内容放在一个文件中。使用FileOutputStream,我可以做到: ByteArrayOutputStream baos = MyClass.myMethod(); // get my stream FileOutputStream out = new FileOutputStream("somefile"); // I want to write to "somefile" out.writ
,我想使用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
,然后使用通道。newChannel(InputStream in)
,最终使用文件通道。transferFrom()
将遇到同样的问题 您可以从另一端尝试:您可以将FileChannel
包装到OutputStream
中,而不是将ByteArrayOutputStream
包装到OutputStream
,并通过调用out.writeTo来完成写入操作:
ByteArrayOutputStream baos = MyClass.myMethod1();
FileChannel channel = MyClass.myMethod2();
OutputStream out = Channels.newOutputStream(channel);
out.writeTo(baos);
将方法更改为不通过tearrayoutputstream生成。这是一种拙劣的技术,无法扩展。将输出流
或可写字节通道
传递给它,并让它编写自己的输出