IT干货网

IO例题:复制目录

leader 2022年03月12日 编程设计 193 0

IO例题:复制目录

以下代码使用IO把硬盘上的一个目录文件复制到硬盘上另一个地方:

package com.javalearn.io.copyall; 
 
import java.io.*; 
 
public class TestForCopy { 
    public static void main(String[] args) { 
        File srcFile = new File("D:\\typora笔记\\java\\io流\\临时文件夹");  //想要复制临时文件夹里面的全部内容 
        File desFile = new File("D:\\typora笔记\\java\\io流\\放这里面");   //想把复制的临时文件夹放入“放这里面” 
        copyDir(srcFile,desFile);  //递归 
    } 
    private static void copyDir(File src,File des) { 
        if(src.isFile()) {  // 复制文件 
            FileInputStream in = null; 
            FileOutputStream out = null; 
            try { 
                in = new FileInputStream(src);  // 被复制的文件 
                String path = (des.getAbsolutePath().endsWith("\\")?des.getAbsolutePath():(des.getAbsolutePath()+"\\")) + src.getAbsolutePath().substring(21);  // “临时文件夹”从原文件绝对路径的第21字符开始,path = 目标路径+临时文件夹中的路径+文件名   
                out = new FileOutputStream(path);  //无此文件则新建 
                byte[] bytes = new byte[1024 * 1024];  // 1MB 
                int count = 0; 
                while ((count = in.read(bytes))!=-1) { 
                    out.write(bytes,0,count); 
                } 
                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(); 
                    } 
                } 
            } 
        } 
 
        if (src.listFiles() != null) { 
            File[] files = src.listFiles(); 
            for(File f :files) { 
                if (f.isDirectory()) {  // 复制目录 
                    String srcDir = f.getAbsolutePath(); 
                    String desDir = des.getAbsolutePath().endsWith("\\") ? des.getAbsolutePath():des.getAbsolutePath()+"\\"+srcDir.substring(21);  // 目标路径 + 临时文件夹中的路径 
                    File newFile = new File(desDir); 
                    if(!newFile.exists()) { 
                        newFile.mkdirs(); 
                    } 
                } 
                copyDir(f,des); 
            } 
        } 
 
    } 
} 
 

评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!