java简单实现复制文件

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("数据读写完成.....");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值