欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IO流--多级文件夹下的所有目录复制到指定目录下

程序员文章站 2024-03-09 09:56:11
...

如题:

/**
 * 将多级目录H:\\aa  目录下,.java   复制到   h:\\cc下
 * @author ZYxiao
 *
 */
public class CopyFileFolder {
    public static void main(String[] args) throws IOException {
        File inputFile = new File("h:\\aa");
        File outputFileFolder = new File("h:\\cc");

        if(!outputFileFolder.exists()){
            outputFileFolder.mkdir();
        }

        copyFolder(inputFile,outputFileFolder);


    }
/**
 * 判断文件文件夹
 * @param inputFile
 * @param outputFileFolder
 * @throws IOException
 */
    private static void copyFolder(File inputFile, File outputFileFolder) throws IOException {
        if(inputFile.isDirectory()){
            File fileFolder = new File(outputFileFolder,inputFile.getName());//要在目标文件夹下创建和源文件夹的子文件夹一样的文件夹
            fileFolder.mkdir();

            File[] files=inputFile.listFiles();
            for (File file : files) {
                copyFolder(file, fileFolder);  //将子目录复制到新生成的文件夹下
            }
        }else{
            File file = new File(outputFileFolder,inputFile.getName());
            copyFile(inputFile,file);
        }
    }

    /**
     * 复制文件
     * @param inputFile
     * @param outputFile
     * @throws IOException
     */
    private static void copyFile(File inputFile, File outputFile) throws IOException {
        // TODO Auto-generated method stub

        BufferedInputStream bis=new BufferedInputStream(new FileInputStream(inputFile));
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(outputFile));

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

        bis.close();
        bos.close();

    }
}

相关标签: io流