JavaSE: Copy all files in a folder to another location (File+recursive)

package com.itheima.d1_fileClone;

import java.io.*;

public class DirectoryCopy {
    public static void main(String[] args) throws Exception {
        copyDirectory(new File("F:\\one"),new File("G:\\"));
    }
    public static void copyDirectory(File oriFile, File newFile) throws Exception {
        //先找到文件目录:有这个目录,不是空的
        if (oriFile!=null && oriFile.isDirectory()){
            //目标位置,创建目录
            File newPath = new File(newFile,oriFile.getName());
            newPath.mkdirs();
            //得到目录下的所有文件
            File[] files = oriFile.listFiles();
            //先判断文件是不是空的,再遍历文件
            if (files!=null){
                for (File fileEach:files){
                    if (fileEach.isFile()){
                        copyFile(fileEach,new File(newPath,fileEach.getName()));
                    }else {
                        copyDirectory(fileEach,newPath);
                    }
                    //文件如果是 文件类型就复制,文件夹就递归
                }
            }


        }
        else {
            System.out.println("没有这个文件夹,路径错误!");
        }



    }
    public static void copyFile(File InpFile,File OutFile) throws Exception {
        //单纯复制文件
        OutputStream os = new FileOutputStream(OutFile);
        InputStream is = new FileInputStream(InpFile);
        //得到两个流:输入输出
        byte[] buffer = new byte[1024];
        while (is.read(buffer)!=-1){
            os.write(buffer);
        }
        System.out.println("该文件复制完毕");
        //while复制
        os.close();
        is.close();
        //复制完了就关了is 和 os
    }
}

Two functions: One gets all the files in the original directory and traverses them. If it is judged to be a file, it calls the function of copying the file. If it is not a file (folder), it needs to recurse. The other is the file copy function.

When I wrote it myself while (is.read(buffer)!=-1), the line was written as while (is.read(buffer)!=0) and the effect was directly reversed. The result was that the first file copied was very large. , cannot be opened.

So I searched for the read function of the byte input stream:

It means that after reading to the end, it will return -1

It’s really important to check the documentation, so I’ll write it here

 

 

Guess you like

Origin blog.csdn.net/qq_54508596/article/details/126066680