文件夹迁移程序设计
要点
1.递归思想,循环调用迁移方法
2.字符串拼接,对文件夹目录路径进行拼接
3.fileInputStream和fileOutputStream流传输数据的应用
package com.ultraBlast.dao;
import java.io.*;
/**
* @Auther: UltraBlast
* @Date : 2021/3/7 - 03 - 07 - 2021 - 17:02
* @Description : com.ultraBlast.dao
* @version: 1.0
*/
public class CopyTest {
public static void main(String[] args) {
File srcFile = new File("path");
File destFile = new File("destPath");
copyDir(srcFile, destFile);
}
private static void copyDir(File srcFile, File destFile) {
if (srcFile.isFile()) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\") + srcFile.getAbsolutePath().substring(3);
fos = new FileOutputStream(path);
byte[] readArr = new byte[1024 * 1024];
int readIndex = 0;
//readIndex = fis.read(readArr);
while ((readIndex = fis.read(readArr)) != -1) {
fos.write(readArr, 0, readIndex);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
return;
}
File[] files = srcFile.listFiles();
for (File file : files) {
if (file.isDirectory()) {
String srcDir = file.getAbsolutePath();
String destDir = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\") + srcDir.substring(3);
File newFile = new File(destDir);
if (!newFile.exists()) {
newFile.mkdirs();
}
}
copyDir(file, destFile);
}
}
}
浙公网安备 33010602011771号