文件通道FileChannel是用于读取,写入,文件的通道。FileChannel只能被InputStream、OutputStream、RandomAccessFile创建。使用fisChannel.transferTo()可以极大的提高文件的复制效率,他们读和写直接建立了通道,还能有效的避免文件过大导致内存溢出。
java.nio.channels.FileChannel (抽象类):用于读、写文件的通道。
下面来说下FileChannel的基本用法:
import java.io.*;
import java.nio.channels.FileChannel;
/**
* 测试0.9G文件,FileChannel的效率
* 耗时=703ms
*/
public class FileChannel的基本用法 {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
File sourceFile = new File("D:/TEST/testFile0.9G文件.zip");
FileInputStream fis = new FileInputStream(sourceFile);
FileChannel fisChannel = fis.getChannel();
FileOutputStream fos = new FileOutputStream("D:/TEST/0.9G文件.zip");
FileChannel fosChannel = fos.getChannel();
//将fisChannel通道的数据,写入到fosChannel通道
fisChannel.transferTo(0, fisChannel.size(), fosChannel);
fis.close();
fos.close();
long end = System.currentTimeMillis();
System.out.println("耗时=" + (end - start) + "ms");
}
}
通过这个案例可以看出复制文件的速度是非常快的。fileChannel能直接连接输入输出流的文件通道,将数据直接写入到目标文件中,达到了提高效率的目的。