java 使用 FileChannel 编写任何 InputStream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6619516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using FileChannel to write any InputStream?
提问by KiKi
Can I write any InputStream into a FileChannel?
我可以将任何 InputStream 写入 FileChannel 吗?
I'm using java.nio.channels.FileChannel to open a file and lock it, then writing a InputStream to the output file. The InputStream may be opened by another file, URL, socket, or anything. I've write the following codes:
我正在使用 java.nio.channels.FileChannel 打开一个文件并锁定它,然后将 InputStream 写入输出文件。InputStream 可以被另一个文件、URL、套接字或任何东西打开。我写了以下代码:
FileOutputStream outputStream = new FileOutputStream(outputFile);
FileChannel outputChannel = outputStream.getChannel();
FileLock lock = outputChannel.lock();
try {
outputChannel.transferFrom(???);
} finally {
lock.release();
outputChannel.close();
outputStream.close();
}
However, the first argument of outputChannel.transferFrom(...) requests a ReadableByteChannel object. Since I an using a InputStream as input, it do not have inputStream.getChannel() method to create the required channel.
但是, outputChannel.transferFrom(...) 的第一个参数请求 ReadableByteChannel 对象。由于我使用 InputStream 作为输入,它没有 inputStream.getChannel() 方法来创建所需的通道。
Is there any way to get a ReadableByteChannel from a InputStream?
有没有办法从 InputStream 获取 ReadableByteChannel?
回答by Kal
Channels.newChannel(InputStream in)
http://docs.oracle.com/javase/7/docs/api/java/nio/channels/Channels.html
http://docs.oracle.com/javase/7/docs/api/java/nio/channels/Channels.html
回答by Amlan Chatterjee
You can use ReadableByteChannel readableChannel = Channels.newChannel(myinputstream).
您可以使用 ReadableByteChannel readableChannel = Channels.newChannel(myinputstream)。