Java NIO系列教程(五) 通道之間的數據傳輸

Java NIO系列教程(五) 通道之間的數據傳輸

在 Java NIO 中,若是兩個通道中有一個是 FileChannel,那你能夠直接將數據從一個 channel(譯者注:channel 中文常譯做通道)傳輸到另一個 channel。java

1、通道的基本操做

FileInputStream fis = new FileInputStream("1.png");
FileOutputStream fos = new FileOutputStream("2.png");

//1. 獲取通道
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel();

//2. 分配緩衝區
ByteBuffer buf = ByteBuffer.allocate(1024);

//3. 用通道傳輸數據
while (inChannel.read(buf) != -1) {
    buf.flip();
    outChannel.write(buf);
    buf.clear();
}

2、直接緩衝區拷貝文件

FileChannel inChannel = FileChannel.open(Paths.get("1.png"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("3.png"), 
    StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);

//內存映射文件,直接緩衝區
MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());

byte[] bytes = new byte[inMappedBuf.limit()];
inMappedBuf.get(bytes);
outMappedBuf.put(bytes);

3、transferFrom() 和 transferTo()

FileChannel 的 transferFrom() 方法能夠將數據從源通道傳輸到 FileChannel 中(譯者注:這個方法在 JDK 文檔中的解釋爲將字節從給定的可讀取字節通道傳輸到此通道的文件中)。下面是一個簡單的例子:編程

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

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

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

outChannel.transferFrom(position, count, inChannel);
//inChannel.transferTo(position, count, outChannel);

方法的輸入參數 position 表示從 position 處開始向目標文件寫入數據,count 表示最多傳輸的字節數。若是源通道的剩餘空間小於 count 個字節,則所傳輸的字節數要小於請求的字節數。
此外要注意,在 SoketChannel 的實現中,SocketChannel 只會傳輸此刻準備好的數據(可能不足 count 字節)。所以,SocketChannel 可能不會將請求的全部數據(count 個字節)所有傳輸到 FileChannel 中。併發

轉載自併發編程網 – ifeve.com,本文連接地址: Java NIO系列教程(二) Channelapp

相關文章
相關標籤/搜索