只针对于" xxxxxx.xxx "类型的文件,例如:aa.txt、今日报告.ppt、风景.jpg
public static void main(String[] args) throws IOException {
//统计某个文件目录下的文件类型,或复制某个文件目录下的文件,这个文件目录就是资源完整路径
String source = "资源完整路径";
//拷贝文件所存放的文件目录就是存放地址
String dest = "拷贝文件的存放地址";
//调用方法,这个方法时复制和统计一起执行
HashMap<String, Integer> count = getAndCopyCount(new HashMap<String, Integer>(), new File(source),dest);
//打印统计的结果
count.forEach((s, integer) -> System.out.println(s + "文件类型的个数:" + integer));
}
private static HashMap<String, Integer> getAndCopyCount(HashMap<String, Integer> hashMap, File src,String dest) throws IOException {
//1、首先获取当前文件夹的所有内容的file对象
File[] files = src.listFiles();
//2、遍历对象
for (File file : files) {
//3.1、判断是不是文件,是的话继续执行
if (file.isFile()){
//一般文件形式:a.txt、a.java、a.xls,所有使用分隔符
String fileName = file.getName();
String[] fileNameArr = fileName.split("\\.");
//4、只取一般文件形式
if (fileNameArr.length == 2){
//文件后缀名例如:txt、ppt、jpg
if ("文件后缀名".equals(fileNameArr[1])){
//因为递归好像出现某些问题。我就用if直接解决了,但只解决了表面,问题底层我没管
if (!(fileNameArr[0].contains("~$"))){
//copy方法1:缓冲流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file.toString()));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest+fileName));
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1){
bos.write(bytes,0,len);
}
bis.close();
bos.close();
//copy方法2:Files
//Path path = Paths.get(String.valueOf(file));
//Files.copy (path,new FileOutputStream (new File (dest+fileName)));
}
}
//5.1、判断该文件类型是否已经存在,存在就+1
if (hashMap.containsKey(fileNameArr[1])){
Integer count = hashMap.get(fileNameArr[1]);
count++;
hashMap.put(fileNameArr[1],count);
}else {//5.1、判断该文件类型是否已经存在,不存在就创建一个键值对对象
hashMap.put(fileNameArr[1],1);
}
}
//3.1、判断为文件夹,需要调用递归
}else {
getAndCopyCount(hashMap,file,dest);
}
}
return hashMap;
}