public class FileCopyTest {
public static void fileCopy(File file,String path){
String oldfilepath=file.getAbsolutePath().split(":")[1];//获取新文件的路径
String newfilepath=path+oldfilepath;
File[] files=file.listFiles();
File newfile=new File(newfilepath);
if(file.isDirectory()){ 判断当前文件是否是文件夹是的话在新文件下创建此文件夹
newfile.mkdir();
if(files.length!=0){ 判断文件夹里是否有文件夹或者文件,递归操作
for(File f:files){
fileCopy(f,path);
}
}
}
else { 读取旧文件,写入带新文件里
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream(file);
fos=new FileOutputStream(newfile);
byte[] b=new byte[1024];
int len=fis.read(b);
while(len!=-1){
fos.write(b,0,len);
len=fis.read(b);
fos.flush();
}
System.out.println("文件:"+file.getName()+"复制成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
File file=new File("F:\\2019-10-09-图书管理系统"); //将F盘中的文件复制到G盘中
String newpath="G:";
fileCopy(file,newpath);
}
}
结果:
源文件
复制的文件: