- 第四题
需求:删除一个多级文件夹
import java.io.File;
/**
* 删除一个多级目录
*/
public class FileDeletion {
public static void main(String[] args) {
File f = new File("H:\\test\\aaa");
deleteDir(f);
}
public static void deleteDir(File dir){
// 进入目录
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
// 如果是文件,则删除
if (file.isFile()){
file.delete();
}else {
// 如果是文件夹,则递归
deleteDir(file);
}
}
// 最后,删除目录本身
dir.delete();
}
}
}
- 第五题
需求:统计一个文件夹中每种文件的个数并打印。 (考虑子文件夹)
①打印格式如下:
②txt:3个
③doc:4个
④jpg:6个
先导题:需求:统计一个文件夹的总大小
参考代码如下:
import java.io.File;
public class FileLenCount {
public static void main(String[] args) {
long len = 0;
String dir = "G:\\JavaCode\\PuzzleGame";
File f = new File(dir);
len = countLen(f);
System.out.println(len);
}
/**
* 统计文件夹的总大小
* @param dir 文件夹
* @return 文件加大小(字节)
*/
public static long countLen(File dir){
long len = 0;
// 列出目录中所有内容
File[] files = dir.listFiles();
if (files != null){
for (File file : files) {
// 1.如果是文件,统计其大小
if (file.isFile()){
len += file.length();
}else {
// 2. 如果是文件夹,则递归
len += countLen(file);
}
}
}
return len;
}
}
然后是统计各种文件类型数量的实现,使用Map存储,key为String类型表示文件扩展名,value为Integer类型,表示对应扩展名文件的数量。参考代码如下:
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class FileTypeCount {
public static void main(String[] args) {
long len = 0;
String dir = "G:\\JavaCode\\PuzzleGame";
File f = new File(dir);
HashMap<String, Integer> hm = countTypeCount(f);
System.out.println(hm);
}
/**
* 统计文件夹的总大小
* @param dir 文件夹
* @return 文件加大小(字节)
*/
public static long countLen(File dir){
long len = 0;
// 列出目录中所有内容
File[] files = dir.listFiles();
if (files != null){
for (File file : files) {
// 1.如果是文件,统计其大小
if (file.isFile()){
len += file.length();
}else {
// 2. 如果是文件夹,则递归
len += countLen(file);
}
}
}
return len;
}
/**
* 文件夹下文件类型的统计
* @param dir 文件夹目录
* @return
*/
public static HashMap<String, Integer> countTypeCount(File dir){
HashMap<String, Integer> hm = new HashMap<>();
// 列出目录中所有内容
File[] files = dir.listFiles();
if (files != null){
for (File file : files) {
// 1.如果是文件,则统计其大小
if (file.isFile()){
// 获取后缀名。注意点.前面要加双斜线,因为split方法参数是regex正则,
// 在正则中点号代码任意一个字符,所以需要转义
String[] split = file.getName().split("\\.");
if (split.length > 1){
String typeName = split[split.length - 1];
// 如果后缀名已有统计,则更新
if (hm.containsKey(typeName)){
hm.put(typeName, hm.get(typeName) + 1);
}else {
// 如果后缀名没有统计,则添加
hm.put(typeName, 1);
}
}
}else {
// 2. 如果是文件夹,则递归
HashMap<String, Integer> subMap = countTypeCount(file);
// 获取子文件夹的统计,更新到hm中
Set<Map.Entry<String, Integer>> entries = subMap.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
// 如果hm中已含文件类型统计,则更新
if (hm.containsKey(entry.getKey())){
hm.put(entry.getKey(), hm.get(entry.getKey()) + entry.getValue());
}
// 如果hm中不含文件类型统计,则添加
hm.put(entry.getKey(), entry.getValue());
}
}
}
}
return hm;
}
}