1,复制单级文件夹
package CasePackage;
import java.io.*;
public class CopyFoldDemo1 {
public static void main(String[] args) throws IOException{
File srcFolder=new File("G:\\JAVA1");
String srcFoldername=srcFolder.getName();
File aimFolder=new File("F:\\0923",srcFoldername);
if(!aimFolder.exists()){
aimFolder.mkdir();
}
File[] listFiles = srcFolder.listFiles();
for(File srcFile:listFiles){
String srcFileName=srcFile.getName();
File aimfile=new File(aimFolder,srcFileName);
copy(srcFile,aimfile);
}
}
private static void copy(File srcFile, File aimfile) throws IOException{
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(aimfile));
byte[] bys=new byte[1024];
int len;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
bis.close();
bos.close();
}
}
2,复制多级文件夹,要用到递归。
package CasePackage;
import java.io.*;
public class CopyFoldersDemo2 {
public static void main(String[] args) throws IOException{
File srcFile=new File("G:\\JAVA2");
File aimFile=new File("F:\\0923");
copyFolders(srcFile,aimFile);
}
//复制多级文件夹的函数
private static void copyFolders(File srcFile, File aimFile) throws IOException{
if(srcFile.isDirectory()){
String srcFileName = srcFile.getName();
File newFolder=new File(aimFile,srcFileName);
if(!newFolder.exists()){
newFolder.mkdir();
}
File[] listFiles = srcFile.listFiles();
for(File file:listFiles){
copyFolders(file,newFolder);
}
}else {
File newFile=new File(aimFile,srcFile.getName());
copyFile(srcFile,newFile);
}
}
//读取单级文件的函数
private static void copyFile(File srcFile, File aimfile) throws IOException {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(aimfile));
byte[] bys=new byte[1024];
int len;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
bis.close();
bos.close();
}
}