Java 实现文件复制的不同方法

用不同的方法实现文件的复制

1. 通道

Channel,它是一个对象,可以通过它读取和写入数据。拿NIO与原来的I/O比较,通道就像是流。是对接操作系统底层和缓冲区的桥梁。

2. 性能比较

内存映射最快,其次是NIO读写文件,再其次是加了缓冲的IO流,最后是无缓冲的IO流

代码示例

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;


public class ChannelDemo {

	public static void main(String[] args) {
		copyFile();
		randomAccessFileCopy();
	}

	/**
	 * 使用内存映射实现文件的复制
	 */
	private static void randomAccessFileCopy() {
		try {
			RandomAccessFile in = new RandomAccessFile("F:/test.txt", "r");
			RandomAccessFile out = new RandomAccessFile("F:/testbak2.txt", "rw");
			
			FileChannel fcIn = in.getChannel();
			FileChannel fcOut = out.getChannel();
		
			long size = fcIn.size();//输入流的字节大小
		
			// 将输入流映射到缓冲区
			MappedByteBuffer inBuf = fcIn.map(MapMode.READ_ONLY, 0, size);
			MappedByteBuffer outBuf = fcOut.map(MapMode.READ_WRITE, 0, size);
			
			// 将输入流缓冲区的内容写到输出流缓冲区
			for(int i = 0; i < size; i++) {
				outBuf.put(inBuf.get());
			}
		
			// 关闭(关闭通道时会写入)
			fcIn.close();
			fcOut.close();
			in.close();
			out.close();
			System.out.println("复制成功");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}// randomAccessFileCopy

	/**
	 * 通过文件通道实现文件复制
	 */
	private static void copyFile() {
		try {
			// 创建一个输入文件通道
			FileChannel fcIn = new FileInputStream("F:/test.txt").getChannel();
			// 创建一个输出文件通道
			FileChannel fcOut = new FileOutputStream("F:/testbak.txt").getChannel();
		
			 ByteBuffer buf = ByteBuffer.allocate(1024);
			 while(fcIn.read(buf) != -1) {
				 buf.flip();
				 fcOut.write(buf);
				 buf.clear();// 清空缓冲区
			 }
		 
			 fcOut.close();
			 fcIn.close();
			 System.out.println("复制成功");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}// copyFile

}
posted on 2019-05-20 12:08  行之间  阅读(584)  评论(0编辑  收藏  举报