1. 程式人生 > >Java NIO教程(五) 通道之間的資料傳輸

Java NIO教程(五) 通道之間的資料傳輸

                                 Java NIO教程(五) 通道之間的資料傳輸


在Java NIO中,如果兩個通道中有一個是FileChannel,那你可以直接將資料從一個channel(譯者注:channel中文常譯作通道)傳輸到另外一個channel。

transferFrom()

FileChannel的transferFrom()方法可以將資料從源通道傳輸到FileChannel中(譯者注:這個方法在JDK文件中的解釋為將位元組從給定的可讀取位元組通道傳輸到此通道的檔案中)。下面是一個簡單的例子:

RandomAccessFile fromFile = new RandomAccessFile( "fromFile.txt", "rw" );
FileChannel      fromChannel = fromFile.getChannel( );

RandomAccessFile toFile = new RandomAccessFile( "toFile.txt", "rw" );
FileChannel      toChannel = toFile.getChannel( );

long position = 0;
long count = fromChannel.size( );

toChannel.transferFrom( position, count, fromChannel );

方法的輸入引數position表示從position處開始向目標檔案寫入資料,count表示最多傳輸的位元組數。如果源通道的剩餘空間小於 count 個位元組,則所傳輸的位元組數要小於請求的位元組數。

此外要注意,在SoketChannel的實現中,SocketChannel只會傳輸此刻準備好的資料(可能不足count位元組)。因此,SocketChannel可能不會將請求的所有資料(count個位元組)全部傳輸到FileChannel中。

transferTo()

RandomAccessFile fromFile = new RandomAccessFile( "fromFile.txt", "rw" );
FileChannel      fromChannel = fromFile.getChannel( );

RandomAccessFile toFile = new RandomAccessFile( "toFile.txt", "rw" );
FileChannel      toChannel = toFile.getChannel( );

long position = 0;
long count = fromChannel.size( );

fromChannel.transferTo( position, count, toChannel );


是不是發現這個例子和前面那個例子特別相似?除了呼叫方法的FileChannel物件不一樣外,其他的都一樣。 上面所說的關於SocketChannel的問題在transferTo()方法中同樣存在。SocketChannel會一直傳輸資料直到目標buffer被填滿。