用java写一个简单的将a目录下文件拷贝到b目录下
时间: 2024-03-11 21:49:13 浏览: 17
可以使用Java的文件操作类来实现这个功能,具体代码如下:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
// 定义源文件和目标文件路径
String sourcePath = "a/";
String targetPath = "b/";
// 创建源文件和目标文件对象
File sourceFile = new File(sourcePath);
File targetFile = new File(targetPath);
// 如果目标文件夹不存在,则创建目标文件夹
if (!targetFile.exists()) {
targetFile.mkdir();
}
// 获取源文件夹下的所有文件
File[] files = sourceFile.listFiles();
// 遍历源文件夹下的所有文件,并拷贝到目标文件夹下
for (File file : files) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(targetPath + file.getName());
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("文件拷贝完成!");
}
}
```
上述代码中,我们首先定义了源文件路径和目标文件路径,然后创建了源文件和目标文件对象。接着,我们判断目标文件夹是否存在,如果不存在则创建目标文件夹。然后获取源文件夹下的所有文件,遍历源文件夹下的所有文件,并将每个文件拷贝到目标文件夹下。最后输出“文件拷贝完成!”的提示信息。