java程序,将一个目录的所有复制到另一个目录下
时间: 2023-03-28 10:01:48 浏览: 79
你可以使用Java的File类和IO流来实现这个功能。首先,使用File类获取源目录和目标目录的路径,然后使用File类的listFiles()方法获取源目录下的所有文件和子目录,遍历这些文件和子目录,如果是文件,则使用IO流将其复制到目标目录下,如果是子目录,则递归调用该方法,将子目录下的所有文件和子目录复制到目标目录下。具体实现可以参考以下代码:
```java
import java.io.*;
public class CopyDirectory {
public static void main(String[] args) {
String sourcePath = "source directory path";
String targetPath = "target directory path";
copyDirectory(sourcePath, targetPath);
}
public static void copyDirectory(String sourcePath, String targetPath) {
File source = new File(sourcePath);
File target = new File(targetPath);
if (!source.exists() || !source.isDirectory()) {
System.out.println("源目录不存在或不是目录!");
return;
}
if (!target.exists()) {
target.mkdirs();
}
File[] files = source.listFiles();
for (File file : files) {
if (file.isFile()) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(new File(target, file.getName()));
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, , len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (file.isDirectory()) {
copyDirectory(file.getAbsolutePath(), new File(target, file.getName()).getAbsolutePath());
}
}
}
}
```