首页 / JAVA / Java实现文件和文件夹复制
Java实现文件和文件夹复制
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java实现文件和文件夹复制,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2192字,纯文字阅读大概需要4分钟。
内容图文
![Java实现文件和文件夹复制](/upload/InfoBanner/zyjiaocheng/607/56062e80ad33418da42671704ee8c91c.jpg)
实现方法
public Boolean copyFile(String srcPath, String desPath)
public Boolean copyFiles(String srcPath, String desPath)
public Boolean copyFile(String srcPath, String desPath)
这个方法当做工具,用于复制单个文件
public Boolean copyFile(String srcPath, String desPath) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//创建文件类对象
File srcFile = new File(srcPath);
File desFile = new File(desPath);
//创建节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(desFile);
//创建处理流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//处理数据
byte[] buffer = new byte[1024 * 50];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
//关闭流
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public Boolean copyFiles(String srcPath, String desPath)
这个方法是具体功能逻辑实现
/**
*
* @param srcPath 原文件目录
* @param desPath 复制文件所在位置
* @return 返回是否复制成功
*/
public Boolean copyFiles(String srcPath, String desPath) {
//创建文件类对象
File srcFile = new File(srcPath);
//真正的文件目录
String realPath = desPath + File.separator + srcFile.getName();
File destFile = new File(realPath);
//判断是否是文件夹
if (srcFile.isDirectory()) {
//如果是文件夹的话,则复制文件夹的所有文件
//需要在目标位置创建新文件夹
destFile.mkdirs();
File[] files = srcFile.listFiles();
for (File f : files) {
String filePath = f.toString();
String tempPath = realPath + File.separator + f.getName();
if (f.isDirectory()) {
//如果文件夹里有文件夹
copyFiles(filePath, tempPath);
} else {
copyFile(filePath, tempPath);
}
}
return true;
} else {
copyFile(srcPath, realPath);
return true;
}
}
功能演示
改代码是将gradle-5.6.4.zip文件复制到桌面,并且输出所需要的的时间
@Test
public void test3() {
String srcPath = "D:\\BaiduNetdiskDownload\\gradle-5.6.4.zip";
String desPath = "C:\\Users\\Ht\\Desktop";
long start = System.currentTimeMillis();
copyFiles(srcPath, desPath);
long end = System.currentTimeMillis();
System.out.println(end - start);
}
内容总结
以上是互联网集市为您收集整理的Java实现文件和文件夹复制全部内容,希望文章能够帮你解决Java实现文件和文件夹复制所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。