Requirements: the E disk folder aaa all content (including aaa folder) copied to disk F
realization of ideas:
- The file folder path E aaa disk package is a File object
- Create a copy function, function parameter file as a File object
- In the copy function
- The first step: parameter file path judgment whether there exists into the second step, the output does not exist
- Step 2: Use getPath () method to obtain the parameter file path, and replace the disc path F, and then packaged into a File object destFile
- The third step: to determine whether the path is a file folder at the end
- Step Four: If it is, get from all subfolders (including folders) and traversal, traversing the destFile to create the folder, and then copy a recursive function
- Step five: If it is not, that end of the file, the file is read and copied to the corresponding disk F get directory
- Specific code as follows:
import java.io.*;
public class CopyDemo {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
String path = "E:/aaa";//文件夹(绝对)路径
File file = new File(path);
copyFile(file);
long end = System.currentTimeMillis();
System.out.println("复制共耗时:"+(end-start)+"毫秒");
}
private static void copyFile(File file) throws Exception {
//判断file对象的文件路径是否存在
if(file.exists()){
//F盘文件路径,File对象无论路径存在与否都可以创建
File destFile = new File(file.getPath().replace("E:","F:"));
if(file.isDirectory()){
//file路径是文件夹结尾
File[] files = file.listFiles();//file的子文件
// 因为file是文件夹结尾才进入此for循环,所以此处destFile也是文件夹结尾
for (File f :
files) {
if(!destFile.exists()){
//目标文件夹不存在则创建
destFile.mkdir();
}
copyFile(f);//递归
}
}else{
//file路径是文件结尾,那么destFile路径也是文件结尾
//读取文件对象
InputStream is = new FileInputStream(file);
//写入文件对象
OutputStream os = new FileOutputStream(destFile);//destFile路径文件不存在会自动创建
int len;//读取的有效字节个数
byte[] b = new byte[1024];
while ((len=is.read()) != -1){
//读取操作返回值为-1则说明读取完毕
os.write(len);//写入数据
}
is.close();//关闭写入
os.close();//关闭读取
}
}else{
System.out.println(file.getPath()+"不存在");
}
}
}