将一个文件夹的文件递归复制到另外一台服务器上,java
时间: 2023-05-16 11:06:51 浏览: 101
可以使用Java的File类和IO流来实现递归复制文件夹。以下是一个示例代码:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
File sourceFolder = new File("sourceFolder");
File targetFolder = new File("targetFolder");
copyFolder(sourceFolder, targetFolder);
}
public static void copyFolder(File sourceFolder, File targetFolder) {
if (sourceFolder.isDirectory()) {
if (!targetFolder.exists()) {
targetFolder.mkdir();
}
String[] files = sourceFolder.list();
for (String file : files) {
File sourceFile = new File(sourceFolder, file);
File targetFile = new File(targetFolder, file);
copyFolder(sourceFile, targetFile);
}
} else {
try {
InputStream in = new FileInputStream(sourceFolder);
OutputStream out = new FileOutputStream(targetFolder);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
这个代码会将sourceFolder文件夹中的所有文件和子文件夹递归复制到targetFolder文件夹中。如果targetFolder不存在,会自动创建。
阅读全文