JAVASE_Fileクラス(練習)-ディレクトリコピー

実装コード

package Filecopy01;

import java.io.*;

/*
* 拷贝源
*
* */
public class CopyAll {
    
    
    public static void main(String[] args) {
    
    
        //拷贝源
        File srcFile=new File("G:\\植物大战僵尸年度英文版");

        //拷贝目标
        File destFile=new File("E:\\");

        //调用拷贝方法
        copyDir(srcFile,destFile);
    }

    private static void copyDir(File srcFile,File destFile){
    
    
        if(srcFile.isFile()){
    
    
            FileInputStream in=null;

            FileOutputStream out=null;

            try {
    
    
                //读这个文件
                in=new FileInputStream(srcFile);
            //写到这个文件中
                String destDir=(destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\")+srcFile.getAbsolutePath().substring(3);

                out=new FileOutputStream(destDir);

                //一边读一边写
                byte[]bytes=new byte[1024*1024];
                int readCount=0;
                while((readCount=in.read(bytes))!=-1)
                {
    
    
                    out.write(bytes,0,readCount);
                }
                out.flush();

            } catch (FileNotFoundException e) {
    
    
                e.printStackTrace();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            } finally {
    
    
                if(in!=null){
    
    
                    try {
    
    
                        in.close();
                    } catch (IOException e) {
    
    
                        e.printStackTrace();
                    }
                }
                if(out!=null){
    
    
                    try {
    
    
                        out.close();
                    } catch (IOException e) {
    
    
                        e.printStackTrace();
                    }
                }
            }

            //如果是一个文件的话,递归结束
            return;
        }
        File []files=srcFile.listFiles();
        for(File file:files){
    
    
            if(file.isDirectory()){
    
    
                String srcDir=file.getAbsolutePath();
                String destDir=(destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\")+srcDir.substring(3);
                File newFile=new File(destDir);
                if(!newFile.exists()){
    
    
                    newFile.mkdirs();
                }
            }
            //递归调用
            copyDir(file,destFile);
        }

    }
}

スクリーンショットを実現する

実行前のスクリーンショット

ここに画像の説明を挿入します

ここに画像の説明を挿入します

ここに画像の説明を挿入します

実行後のスクリーンショット

ここに画像の説明を挿入します
ここに画像の説明を挿入します

おすすめ

転載: blog.csdn.net/CSNN2019/article/details/114400336