Java学习笔记——通过通道复制文件transferTo

通过通道来实现文件的复制操作,具体实现代码如下:

import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.*;
import java.io.IOException;
import java.util.EnumSet;

public class FileBackup {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成方法存根
		Path file = Paths.get(System.getProperty("user.home")).resolve(
				"Beginning Java Stuff").resolve("Sayings.txt");
		if (!Files.exists(file)) {
			System.err.println(file + " is not exist.");
			System.exit(1);
		}
		file.toAbsolutePath();//将路径转化为绝对路径,如果已经是绝对路径则原样返回
		Path tofile= createBackupFilePath(file);//创建复制文件路径
		try{
			FileChannel inCh=(FileChannel)(Files.newByteChannel(file));//filechannel具有更高的功能
			WritableByteChannel outCh=Files.newByteChannel(tofile,EnumSet.of(WRITE,CREATE));//新建写入文件通道
			int byteWritten=0;
			long byteCount=inCh.size();
			while(byteWritten<byteCount){
				byteWritten+=inCh.transferTo(byteWritten,byteCount-byteWritten,outCh);
				//Transfers bytes from this channel's file to the given writable byte channel.
				//long transferTo(long position,long count,WritableByteChannel target) position是开始位置,count是要读取的字节数,target是目标通道
				//返回的是实际转化的字节数
			}
			System.out.printf("File copy complete. %d bytes copied to %s%n", byteCount, tofile);
		}catch(IOException e){
			e.printStackTrace();
		}
		
	}
    public static Path createBackupFilePath(Path file){
    	Path parent=file.getParent();
    	String name=file.getFileName().toString();//getFilename返回文件名(路径类型),也就是路径中距离根目录最远的
    	int period=name.indexOf('.');
    	if(period==-1){
    		period=name.length();
    	}
    	String nameAdd="_backup";
    	Path backup=parent.resolve(name.substring(0,period)+nameAdd+name.substring(period));//修改路径,建立复制文件路径
    	while(Files.exists(backup)){//检测新建的路径是否存在,如果存在则继续在文件名后面加_backup
    		name=backup.getFileName().toString();
    		backup=parent.resolve(name.substring(0,period)+nameAdd+name.substring(period));
    		period+=nameAdd.length();
    		
    	}
    	return backup;
    }
}
实现结果如下:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值