提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
public class Test {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
System.out.println("输入源文件夹路径:");
String source=sc.next();
System.out.println("输入目标文件夹路径:");
String targetDirk=sc.next();
int count=dirkCopyFile(source,targetDirk,"java");
System.out.println("java文件的个数为:"+count);
}
//复制文件的函数
public static void copy(String source,String target) throws IOException {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(source));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(target));
byte[] b=new byte[1024];
int len=0;
while ((len=bis.read(b))!=-1){
bos.write(b,0,len);
bos.flush();
}
bos.close();
bis.close();
}
//将source下的type类型文件复制到targetDirk下
public static int dirkCopyFile(String source,String targetDirk,String type) throws IOException {
int count=0;
File file=new File(source);
//如果file是文件就进行复制
if (file.isFile()){
//产生一个目标路径,文件名引用原文件的文件名
File newFile=new File(targetDirk+"\\"+file.getName());
//获取最后一个".",准备截取后缀名。
int index=file.getName().lastIndexOf(".");
//如果是type类型的文件,就进行复制
if(file.getName().substring(index+1).equals(type)) {
//如果targetDirk文件夹下有同名的文件,就修改文件名(目前源文件夹中只有一个同名文件,如果有多个会覆盖)
if (!newFile.exists()) {
copy(file.getAbsolutePath(), targetDirk + "\\" + file.getName());
return 1;
} else {
copy(file.getAbsolutePath(), targetDirk + "\\" + file.getName() + "(1)");
return 1;
}
}
//如果是文件夹就进入下一层文件夹
}else if (file.isDirectory()){
File[] files=file.listFiles();
if (files.length!=0){
for (File f:files){
count+=dirkCopyFile(f.getAbsolutePath(),targetDirk,type);
}
}
}
return count;
}
}