复制多级文件,将一个文件夹中的所有内容复制到另一个文件夹中

复制多级文件,将一个文件夹中的所有内容复制到另一个文件夹中。

设计递归方法,通过传入源文件和目的文件,将源文件中内容完全复制到目的文件中:
代码如下:

private static void copyFolder(File srcFile, File destFile) throws IOException {  //srcFile为源文件,destFile为目的文件
        if (srcFile.isDirectory()) {
            File newFolder = new File(destFile, srcFile.getName());
            newFolder.mkdir();
            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();
    }

public class MyLineNumberReader {private Reader r;private int lineNmber = 0;
public MyLineNumberReader(Reader r) {this.r = r;}
public int getLineNmber() {return lineNmber;}
public void setLineNmber(int lineNmber) {this.lineNmber = lineNmber;}
public String readLine() throws IOException {lineNmber++;                //当读取每一行数据时,相应的行数加一
StringBuilder sb = new StringBuilder();
int ch = 0;while ((ch = r.read()) != -1) {    // 依次读取单个字符if (ch == '\r') {continue;}if (ch == '\n') {         // 当遇到换行符时,输出本行所有数据return sb.toString();} else {sb.append((char) ch);    // 依次存储换行符之前的每个字符}}
if (sb.length() > 0) {        // 为防止数据丢失,判断sb的长度是否大于0return sb.toString();}
return null;}
public void close() throws IOException {this.r.close();}}————————————————版权声明:本文为CSDN博主「流年锦时」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。原文链接:https://blog.csdn.net/qq_36653524/article/details/100154823

猜你喜欢

转载自www.cnblogs.com/LiuNianJinShi/p/11436851.html