Java实现文件和文件夹复制
作者:互联网
实现方法
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,String,复制,desPath,文件夹,File,srcPath,new,public 来源: https://blog.csdn.net/ht_vIC/article/details/113613404