Java implements copying all folders and files in multi-level directories

Project scenario:

Java's IO流practice of copying all folders and files in multi-level directories

For example: demoscopy all folders and files in the folder under the d drive to copydemosthe folder under the d drive.
Key points: Copy the folder and use 递归
the code to enter the following:

import java.io.*;

public class CopyFoldersDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        // 封装数据源File
        File srcFile = new File("d:\\demos");
        // 封装目的地File
        File destFile = new File("d:\\copydemos");
        // 如果目的地文件夹不存在就创建
        if (!destFile.exists()) {
    
    
            destFile.mkdir();
        }

        // 复制文件夹的功能
        copyFolder(srcFile, destFile);
    }

    private static void copyFolder(File srcFile, File destFile) throws IOException {
    
    
        if (srcFile.isDirectory()) {
    
    
            // 文件夹
            File newFolder = new File(destFile, srcFile.getName());
            newFolder.mkdir();

            // 获取该File对象下的所有文件或文件夹File对象
            File[] fileArray = srcFile.listFiles();
            for (File file : fileArray) {
    
    
                copyFolder(file, newFolder);
            }
        } else {
    
    
            // 文件
            File newFile = new File(destFile, srcFile.getName());
            copyFile(srcFile, newFile);
        }
    }

    private static void copyFile(File srcFile, File newFile) throws IOException {
    
    
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1) {
    
    
            bos.write(bys, 0, len);
        }
        bos.close();
        bis.close();
    }
}


Remark:

There are two main reasons for adopting byte-buffered input and output streams in the case:
first, it is efficient (compared to byte input and output streams), and
second, it can copy any type of file such as txt, jpg, mp3, mp4, avi (compared to for character input and output streams)

Java implements copying all files in a single-level directory.
Refer to Liu Yi's JavaSE video

Guess you like

Origin blog.csdn.net/qq_39691492/article/details/129720418