2011-07-08 25 views
6

我可以將任何InputStream寫入FileChannel嗎?我使用java.nio.channels.FileChannel打開文件並將其鎖定,然後將InputStream寫入輸出文件。 InputStream可能被另一個文件,URL,套接字或其他東西打開。我已經寫了下面的代碼:使用FileChannel寫入任何InputStream?

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?

回答

5

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

相關問題