简体   繁体   English

使用 FileChannel 编写任何 InputStream?

[英]Using FileChannel to write any InputStream?

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.我正在使用 java.nio.channels.FileChannel 打开文件并将其锁定,然后将 InputStream 写入 output 文件。 The InputStream may be opened by another file, URL, socket, or anything. InputStream 可能被另一个文件 URL、socket 或任何东西打开。 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.然而, outputChannel.transferFrom(...) 的第一个参数请求一个 ReadableByteChannel object。 Since I an using a InputStream as input, it do not have inputStream.getChannel() method to create the required channel.由于我使用 InputStream 作为输入,因此它没有 inputStream.getChannel() 方法来创建所需的通道。

Is there any way to get a ReadableByteChannel from a InputStream?有什么方法可以从 InputStream 中获取 ReadableByteChannel 吗?

You can use ReadableByteChannel readableChannel = Channels.newChannel(myinputstream).您可以使用 ReadableByteChannel readableChannel = Channels.newChannel(myinputstream)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM