java把e盘中a文件夹里所有文件复制到d盘中b文件夹中
时间: 2023-05-25 11:06:49 浏览: 196
以下是Java实现该操作的代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyExample {
public static void main(String[] args) {
String sourceFolder = "E:/a";
String destinationFolder = "D:/b";
copyFolder(new File(sourceFolder), new File(destinationFolder));
System.out.println("Files copied successfully!");
}
public static void copyFolder(File source, File destination) {
if (source.isDirectory()) {
if (!destination.exists()) {
destination.mkdir();
}
String[] files = source.list();
for (String file : files) {
File srcFile = new File(source, file);
File destFile = new File(destination, file);
copyFolder(srcFile, destFile);
}
} else {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
byte[] buffer = new byte[1024];
try {
inputStream = new FileInputStream(source);
outputStream = new FileOutputStream(destination);
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
该代码会将E盘中的a文件夹中的所有文件和子文件夹复制到D盘中的b文件夹中。如果目标文件夹不存在,则会先创建该文件夹。在每个文件的复制过程中,会使用字节流的方式复制文件内容。最后,程序会输出“Files copied successfully!”的信息表示复制完成。
阅读全文