public void copy(String srcPath, String destPath) throws IOException{
File srcFile = new File(srcPath);
File destFile = new File(destPath);
if (srcFile.exists()) {
if (!destFile.exists()) {
destFile.mkdir();
}
for (File file : srcFile.listFiles()) {
if (file.isFile()) { // 如果是文件就直接复制
String path = destPath + file.getName();
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(new File(path));
byte[] buf = new byte[2048];
int index = -1;
while ((index = fis.read(buf)) != -1) {
fos.write(buf, 0, index);
}
fis.close();
fos.flush();
fos.close();
} else if (file.isDirectory()) { // 如果是文件夹则递归进入子文件。
String path = file.getName() + "/";
copy(srcPath + path, destPath + path);
}
}
}
}Java 实现文件复制方法
最新推荐文章于 2026-03-30 01:33:06 发布
本文介绍了一个使用Java实现的文件及文件夹复制的方法。通过递归遍历源目录下的所有文件和子文件夹,并将其复制到目标目录。该方法能够处理文件夹及其包含的所有层级的文件夹和文件。


1403

被折叠的 条评论
为什么被折叠?



