在Java NIO中,可以非常頻繁地將資料從一個通道傳輸到另一個通道。批次傳輸檔案資料是非常普遍的,因為幾個優化方法已經新增到FileChannel
類中,使其更有效率。
通道之間的資料傳輸在FileChannel
類中的兩種方法是:
FileChannel.transferTo()
方法FileChannel.transferFrom()
方法FileChannel.transferTo()方法
transferTo()
方法用來從FileChannel
到其他通道的資料傳輸。
下面來看一下transferTo()
方法的例子:
public abstract class Channel extends AbstractChannel
{
public abstract long transferTo (long position, long count, WritableByteChannel target);
}
FileChannel.transferFrom()方法
transferFrom()
方法允許從源通道到FileChannel
的資料傳輸。
下面來看看transferFrom()
方法的例子:
public abstract class Channel extends AbstractChannel
{
public abstract long transferFrom (ReadableByteChannel src, long position, long count);
}
基本通道到通道資料傳輸範例
下面來看看從4
個不同檔案讀取檔案內容的簡單範例,並將它們的組合輸出寫入第五個檔案:
package com.yiibai;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.nio.channels.WritableByteChannel;
import java.nio.channels.FileChannel;
public class TransferDemo {
public static void main(String[] argv) throws Exception {
String relativelyPath = System.getProperty("user.dir");
// Path of Input files
String[] iF = new String[] { relativelyPath + "/input1.txt", relativelyPath + "/input2.txt",
relativelyPath + "/input3.txt", relativelyPath + "/input4.txt" };
// Path of Output file and contents will be written in this file
String oF = relativelyPath + "/combine_output.txt";
// Acquired the channel for output file
FileOutputStream output = new FileOutputStream(new File(oF));
WritableByteChannel targetChannel = output.getChannel();
for (int j = 0; j < iF.length; j++) {
// Get the channel for input files
FileInputStream input = new FileInputStream(iF[j]);
FileChannel inputChannel = input.getChannel();
// The data is tranfer from input channel to output channel
inputChannel.transferTo(0, inputChannel.size(), targetChannel);
// close an input channel
inputChannel.close();
input.close();
}
// close the target channel
targetChannel.close();
output.close();
System.out.println("All jobs done...");
}
}
在上述程式中,將4
個不同的檔案(即input1.txt
,input2.txt
,input3.txt
和input4.txt
)的內容讀取並將其組合的輸出寫入第五個檔案,即:combine_output.txt
檔案的中。combine_output.txt
檔案的內容如下 -
this is content from input1.txt
this is content from input2.txt
this is content from input3.txt
this is content from input4.txt