在使用传统IO方式进行大文件复制时,效率很低。因为传统IO每次只复制一个字节,下面将会介绍如何使用java的NIO实现文件复制。java的NIO每次复制一个缓冲区到另一个文件,这个缓冲区大小有用户自己定义,因此效率要比传统IO好很多。实例将reader.txt文件的内容复制到reader_output.txt文件。代码如下:
package com.bug315.nio; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class CopyFile { public static void main(String[] args) { FileInputStream input = null; FileOutputStream output = null; FileChannel fci = null; FileChannel fco = null; try { input = new FileInputStream(new File("document/reader.txt")); output = new FileOutputStream(new File("document/reader_output.txt")); fci = input.getChannel(); fco = output.getChannel(); // 读取文件内容 ByteBuffer buffer = ByteBuffer.allocate(1024); int len = fci.read(buffer); while ( len != -1 ) { // 反转缓冲区,即将读取开始下标设置为0 buffer.flip(); // 将数据写入到输出通道 fco.write(buffer); // 将缓冲区清空 buffer.clear(); len = fci.read(buffer); } } catch (Exception e) { e.printStackTrace(); } finally { if ( output != null ) { try { output.close(); output = null; } catch (IOException e) { e.printStackTrace(); } } if ( fco != null ) { try { fco.close(); fco = null; } catch (IOException e) { e.printStackTrace(); } } if ( input != null ) { try { input.close(); input = null; } catch (IOException e) { e.printStackTrace(); } } if ( fci != null ) { try { fci.close(); fci = null; } catch (IOException e) { e.printStackTrace(); } } } // } }