import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 复制单极文件夹中指定文件并修改文件名称
*/
public class Test1 {
public static void main(String[] args) throws IOException{
//源文件
File src = new File("E:\\za");
//目标文件
File des = new File("D:\\");
//判断目标文件是否存在,不存在创建
if (des.exists()) {
des.mkdirs();
}
//调用方法复制文件夹
copyFolder(src, des);
}
//定义用来复制文件夹的方法
public static void copyFolder(File src,File des)throws IOException{
//判断源文件是不是文件
if(src.isFile()){
//是的话获取名称
String name=src.getName();
//判断名称是不是符合指定文件格式
if(name.endsWith(".java")){
//如果是改名
name=name.replace(".java", ".txt");
}
//重新命名新目标文件
File newDes=new File(des,name);
//调用复制文件的方法
copy(src,newDes);
}else {
//不是的话获取名称
String name=src.getName();
//创建新的目标文件夹
File newDes=new File(des,name);
newDes.mkdirs();
//获取源文件下的文件数组
File[] files=src.listFiles();
for(File file:files){
//递归调用
copyFolder(file,newDes);
}
}
}
//定义方法用来复制文件
public static void copy(File src,File des)throws IOException{
//高效字节输入流,指向源文件
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src));
//高效字节输出流,指向目标文件
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(des));
//一次读取一个数组
byte[] by=new byte[1024];
int len=0;
while((len=bis.read(by))!=-1){
//一次写出一个数组的一部分
bos.write(by,0,len);
}
//释放资源
bis.close();
bos.close();
}
} |
|