簡體   English   中英

使用 FileChannel 編寫任何 InputStream?

[英]Using FileChannel to write any InputStream?

我可以將任何 InputStream 寫入 FileChannel 嗎?

我正在使用 java.nio.channels.FileChannel 打開文件並將其鎖定,然后將 InputStream 寫入 output 文件。 InputStream 可能被另一個文件 URL、socket 或任何東西打開。 我寫了以下代碼:

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 object。 由於我使用 InputStream 作為輸入,因此它沒有 inputStream.getChannel() 方法來創建所需的通道。

有什么方法可以從 InputStream 中獲取 ReadableByteChannel 嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM