使用FileChannel写入任何InputStream?
我可以将任何InputStream写入FileChannel吗?
我使用 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();
}
但是,outputChannel.transferFrom(...) 的第一个参数请求 ReadableByteChannel 对象。由于我使用 InputStream 作为输入,因此它没有 inputStream.getChannel() 方法来创建所需的通道。
有什么方法可以从 InputStream 获取 ReadableByteChannel 吗?
Can I write any InputStream into a 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:
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.
Is there any way to get a ReadableByteChannel from a InputStream?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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
您可以使用 ReadableByteChannel ReadableChannel = Channels.newChannel(myinputstream)。
You can use ReadableByteChannel readableChannel = Channels.newChannel(myinputstream).