21xrx.com
2024-09-17 04:31:35 Tuesday
登录
文章检索 我的文章 写文章
如何用Java复制文件夹到另一个文件夹
2023-06-13 21:22:52 深夜i     --     --
Java 文件夹 复制 递归 File类

文章:

在Java中,复制文件夹可以使用File类和一些递归操作来完成。本文将介绍如何用Java复制文件夹到另一个文件夹,包括以下步骤:

1. 创建目标文件夹

2. 遍历原始文件夹中的所有文件和文件夹

3. 复制每个文件和文件夹到目标文件夹中

1. 创建目标文件夹

首先,我们需要创建一个新的文件夹来保存复制的文件夹:


File destFolder = new File("path/to/destination/folder");

destFolder.mkdir();

2. 遍历原始文件夹中的所有文件和文件夹

使用递归操作,我们可以遍历原始文件夹中的所有文件和文件夹:


public void copyFolder(File sourceFolder, File destinationFolder) throws IOException {

  if (sourceFolder.isDirectory()) {

    if (!destinationFolder.exists()) {

      destinationFolder.mkdir();

    }

    String[] files = sourceFolder.list();

    for (String file : files) {

      File srcFile = new File(sourceFolder, file);

      File destFile = new File(destinationFolder, file);

      copyFolder(srcFile, destFile);

    }

  } else {

    InputStream in = new FileInputStream(sourceFolder);

    OutputStream out = new FileOutputStream(destinationFolder);

    byte[] buffer = new byte[1024];

    int length;

    while ((length = in.read(buffer)) > 0) {

      out.write(buffer, 0, length);

    }

    in.close();

    out.close();

  }

}

3. 复制每个文件和文件夹到目标文件夹中

最后,我们需要调用`copyFolder`方法来复制每个文件和文件夹到目标文件夹中:


File sourceFolder = new File("path/to/source/folder");

File destinationFolder = new File("path/to/destination/folder");

copyFolder(sourceFolder, destinationFolder);

以上就是如何用Java复制文件夹到另一个文件夹的全部步骤,希望对你有所帮助。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复