场景:要将 D 盘上的某个文件夹通过 IO 流复制到 E 盘下的某个文件夹中。
实现:
在一个 文件工具类中,通过 IO 流技术,运用递归算法,实现了一个简单的磁盘上文件夹的复制
代码:
public class FileUtil {
/**
* 复制目录
*
* @param srcFile 源文件
* @param destFile 目标文件
*/
public static void copyDir(File srcFile, File destFile) throws Exception{
// 判断是否为文件
if (srcFile.isFile()) {
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream((destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath()
: destFile.getAbsolutePath() + "\\") + srcFile.getAbsolutePath().substring(3));
byte[] bytes = new byte[1024 * 1024];
int len = 0;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
fos.flush();
fis.close();
fos.close();
} else {
// 如果不是文件,则获取它的下级目录
File[] files = srcFile.listFiles();
if (null != files) {
if (files.length > 0) {
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);
}
}
}
}
}
}
通过 main() 方法进行测试:
public static void main(String[] args) throws Exception{
String srcFilePath = "D:\\docs";
String destFilePath = "E:\\zzc\\test\\";
File srcFile = new File(srcFilePath);
if (!srcFile.exists()) {
throw new RuntimeException("此文件路径不存在");
}
File destFile = new File(destFilePath);
// 防止源文件夹中的路径名不会被生成(当遍历源文件夹第一个 File 为文件时,是不会生成 "ttt" 路径名)
String path = (destFilePath.endsWith("\\") ? destFilePath : destFilePath + "\\") + srcFilePath.substring(3);
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
FileUtil.copyDir(srcFile, destFile);
}
我认为,这种场景很典型,所以,这里就把它给记录下来了~~
本文地址:https://blog.csdn.net/Lucky_Boy_Luck/article/details/109266155
您可能感兴趣的文章:
- vue init初始化项目后 npm run dev报错 10% building modules 1/1 modules 0 activeevents
- axios 处理 302 状态码的解决方法
- [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/feature
- react-native 在新版Xcode(10+)中运行出现的问题: node_modules/react-native/third-party/glog-0.3.4 , C compiler cannot create executables
- 使用puppeteer爬取网站并抓出404无效链接
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
网友评论