您的位置:首页 > 编程语言 > Java开发

java简单实现复制文件

2012-09-20 11:43 459 查看
package com.xx.FileChannel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * @author 作者 E-mail: 
 * @version 创建时间:2012-9-20 上午10:49:50 
 * 类说明
 */
public class FileCopy {
	public static void main(String[] args) throws IOException,
			InterruptedException {
		RandomAccessFile In = new RandomAccessFile("c:/aa.exe", "rw");
		FileChannel fileIn = In.getChannel();
		// FileChannel fileIn = new FileInputStream("c:/aa.exe").getChannel();
		FileChannel fileOut = new FileOutputStream("c:/bb.exe").getChannel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		FileLock lock = fileIn.tryLock();
		if (lock == null) {
			System.out.println("文件正在使用....");
			return;
		}
		while ((fileIn.read(buffer)) != -1) {
			buffer.flip();// 重组缓冲区--->>>数据并没有改变,只改变索引键值
			fileOut.write(buffer);// 写入通道中
			buffer.clear();// 清楚缓冲区,已被下次使用
			System.out.println("读写数据.....");
			Thread.currentThread().sleep(500);
		}
		// fileIn.transferTo(0, fileIn.size(), fileOut);速度快
		lock.release();
		fileIn.close();
		fileOut.close();

		System.out.println("数据读写完成.....");
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: