java用有参方法将目录下所有文件复制到另一个目录中
时间: 2023-05-18 22:02:53 浏览: 86
可以使用以下代码实现:
```java
import java.io.*;
public class FileCopy {
public static void copyFiles(String sourceDir, String targetDir) throws IOException {
File source = new File(sourceDir);
File target = new File(targetDir);
if (!source.exists()) {
throw new IllegalArgumentException("Source directory does not exist: " + sourceDir);
}
if (!target.exists()) {
target.mkdirs();
}
if (!source.isDirectory()) {
throw new IllegalArgumentException("Source is not a directory: " + sourceDir);
}
if (!target.isDirectory()) {
throw new IllegalArgumentException("Target is not a directory: " + targetDir);
}
File[] files = source.listFiles();
for (File file : files) {
if (file.isFile()) {
FileInputStream in = new FileInputStream(file);
FileOutputStream out = new FileOutputStream(targetDir + File.separator + file.getName());
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
} else if (file.isDirectory()) {
copyFiles(sourceDir + File.separator + file.getName(), targetDir + File.separator + file.getName());
}
}
}
}
```
然后在主函数中调用:
```java
public static void main(String[] args) throws IOException {
String sourceDir = "C:\\source";
String targetDir = "C:\\target";
FileCopy.copyFiles(sourceDir, targetDir);
}
```
其中,sourceDir 是源目录,targetDir 是目标目录。这个方法会将源目录下的所有文件和子目录复制到目标目录中。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)