复制文件夹中的所有文件到同一目录

    /**
     * 递归遍历所有文件夹,并复制文件
     */
    private static void travelAndCopyFile(File root) {
        if (root.isFile()) {
            File distFile = new File(DIST_FOLDER + "/" + root.getName());
            if (distFile.exists()) {
                distFile.delete();
            }
            copy(root, distFile);
            return;
        } else {
            File [] childFiles = root.listFiles();
            for (File file : childFiles) {
                travelAndCopyFile(file);
            }
        }
    }


    /**
     * 复制文件
     */
    private static void copy(File srcFile, File distFile) {
        try {
            BufferedInputStream reader = new BufferedInputStream(new FileInputStream(srcFile));
            BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(distFile));
            
            byte[] byteBuff = new byte[1024 * 5];
            int len;
            while ((len = reader.read(byteBuff)) != -1) {
                writer.write(byteBuff, 0, len);
            }
            
            writer.flush();
            reader.close();
            writer.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(java)