通过通道复制文件transferTo

飞狐

收藏于 : 2019-06-25 18:41   被转藏 : 1   

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;

    }

}

 阅读文章全部内容  
点击查看
文章点评
相关文章
飞狐 关注

文章收藏:148

TA的最新收藏