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 {

        public static void main(String[] args) {
            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){
                    // Transfers bytes from this channel's file to the given writable byte channel.
                    // long transferTo(long position,long count,WritableByteChannel target)
                    // position是开始位置,count是要读取的字节数,target是目标通道
                    // 返回的是实际转化的字节数
                    byteWritten += inCh.transferTo(byteWritten,byteCount - byteWritten,outCh);
                }
                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;
        }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值