Java I/O流

Java I/O流


用文件通道(FileChannel)来实现文件快速复制

程序运行时间截图

FileChannel方式截图

缓冲输入输出流方式截图

程序代码

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class copyFileChannel {
public static void copy(File a, File temp) {
	FileInputStream fi = null;
	FileOutputStream fo = null;
	FileChannel in = null;
	FileChannel out = null;
	try {
		fi = new FileInputStream(a);
		fo = new FileOutputStream(temp);
		in = fi.getChannel();// 得到对应文件通道
		out = fo.getChannel();// 得到对应文件通道
		in.transferTo(0, in.size(), out);// 连接两个通道
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {

			fi.close();
			fo.close();
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

public static void main(String[] args) {
	// TODO Auto-generated method stub

	File a = new File("a.mp3");
	File temp = new File("temp.mp3");
	long start, end;
	start = System.currentTimeMillis();
	copy(a, temp);
	end = System.currentTimeMillis();
	System.out.println("复制,用时" + (end - start) + "ms");
   }
}
posted @ 2016-04-04 11:46  向上丶的心  阅读(145)  评论(1编辑  收藏  举报