功能介绍
使用Java实现文件夹和文件夹内文件的拷贝工作,使用File、FileInputStream、FileOutputStream完成操作,在拷贝操作的同时输出拷贝进度。
代码部分
拷贝工作的主题是runCopy,runCopy完成以下操作:首先使用buildDic方法,按照待拷贝的文件夹在新的文件位置生成相应的文件夹,然后使用copyAll方法进行拷贝。copyAll方法通过递归进行文件遍历,然后通过调用FileInputStream和FileOutputStream的copyFile方法拷贝每一个文件。
package cn.dango.d20201023.demo05;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class NewDemo {
public static void main(String[] args) throws IOException {
String oldFilesPath = "D:\\Dango";
String newFilesPath = "D:\\new";
runCopy(oldFilesPath, newFilesPath);
}
public static long copyFilesNum = 0;
public static void runCopy(String oldFilePath, String newFilePath) throws IOException {
File oldFile = new File(oldFilePath);
int oldFilePathNum = oldFilePath.length();
buildDic(oldFile, newFilePath, oldFilePathNum);
long allFilesNum = getAllFileNum(oldFile);
System.out.println("一共需要拷贝 " + allFilesNum + " 个文件,现在开始拷贝。");
copyAll(oldFile, newFilePath, allFilesNum, oldFilePathNum);
}
public static void buildDic(File file, String newDic, int oldLength){
File[] files = file.listFiles();
for(File f : files){
if(f.isDirectory()){
new File(newDic.concat(f.getAbsolutePath().substring(oldLength))).mkdirs();
buildDic(f, newDic, oldLength);
}
}
}
public static long getAllFileNum(File file){
File[] files = file.listFiles();
long rNum = 0;
for(File f : files){
if(f.isDirectory()){
rNum += getAllFileNum(f);
}
else{
rNum ++;
}
}
return rNum;
}
public static void copyAll(File file, String newDic, long allNum, int oldLength) throws IOException {
File[] files = file.listFiles();
for(File f : files){
if(f.isDirectory()){
copyAll(f, newDic, allNum, oldLength);
}
else{
String oldFileName = f.getAbsolutePath();
String newFileName = newDic.concat(oldFileName.substring(oldLength));
copyFile(oldFileName, newFileName);
copyFilesNum ++;
System.out.print("已经完成:" + copyFilesNum);
System.out.println(" 共需拷贝:" + allNum + " 。");
}
}
}
public static void copyFile(String oldFile, String newFile) throws IOException {
FileInputStream fis = new FileInputStream(oldFile);
byte[] b = new byte[1024];
int len = 0;
new File(newFile).createNewFile();
FileOutputStream fos = new FileOutputStream(newFile, true);
while(true){
len = fis.read(b);
if(len != 1024){
fos.write(b);
break;
}
else{
fos.write(b);
}
}
fis.close();
fos.close();
System.out.println("文件:" + oldFile + " 已经拷贝完毕。");
}
}