//代码还能优化 采用File IO流 递归 vx:XiaoG23qw
import java.io.*;
public class FileTest06 {
public static void main(String[] args) {
//拷贝的源文件
File srcFile = new File("D:\\笔记");
//目标文件
File destFile = new File("F:\\1");
//测试代码
// System.out.println(srcFile.getAbsolutePath());
// String src = srcFile.getAbsolutePath();
// String dest = destFile.getAbsolutePath();
// String path = (dest.endsWith("\\")?dest:dest+"\\")+src.substring(3);
// System.out.println(path);
// File newFile = new File(path);
// if(!newFile.exists()){
// newFile.mkdirs();
// }
copyFile(srcFile, destFile);
}
private static void copyFile(File srcFile, File destFile) {
//创建File数组 字节输入/输出流
File[] files = srcFile.listFiles();
FileInputStream fis =null;
FileOutputStream fos = null;
byte[] readByte = new byte[102400];
//forE遍历File【】
for(File file:files){
//判断是否是文件
if(file.isDirectory()){
String src = file.getAbsolutePath();
String dest = destFile.getAbsolutePath();
//获取文件夹名
String path = (dest.endsWith("\\")?dest:dest+"\\")+file.getName();
System.out.println(path);
File newFile = new File(path);
//判断文件夹是否存在 不存在创建文件夹
if(!newFile.exists()){
newFile.mkdirs();
}
//方法调用方法
copyFile(file, newFile);
}//这也是方法的出口
else{
try {
int r;
//文件的读和写
fis = new FileInputStream(file);
String path = (destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\")+file.getName();
//System.out.println(file.getName());
System.out.println(path);
fos = new FileOutputStream(path);
while ((r =fis.read(readByte))!=-1){
fos.write(readByte,0,r);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
采用IO file 递归的方法复制文件