import java.io.BufferedReader
import java.io.FileReader
import java.util.*
public static void main(String[] args) throws Exception {
//读文件
try (BufferedReader br = new BufferedReader(new FileReader("D:/words.txt"))) {
HashMap<String, Integer>map = new HashMap<String, Integer>()//建一个存放读取数据的集合
String line = null//每次读取一行
while ((line = br.readLine()) != null) {//循环读入
String[] split = line.split(" ")//切分
for (String word : split) {//遍历字符串数组
if (word.length() != 0) {//判断对象不为空
if (map.containsKey(word)) {//判断集合中是否包括目标单词
map.put(word, map.get(word) + 1)//如果包括,value值+1,如果不包括,将新单词放入集合中
} else {
map.put(word, 1)
}
}
}
}
Set<Map.Entry<String, Integer>>entrySet = map.entrySet()//集合中的元素以k,v形式取出
ArrayList<Map.Entry<String, Integer>>list = new ArrayList<Map.Entry<String, Integer>>(entrySet)//放入List集合中
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {//进行降序排序
@Override//重写比较器
public int compare(Map.Entry<String, Integer>o1, Map.Entry<String, Integer>o2) {
return o2.getValue().compareTo(o1.getValue())
}
})
System.out.println(list)//打印结果
}
}
listFiles方法返回当前目录内所有文件和子目录的File对象数组。获取其大小即文件和子目录的数量总和。
遍历数组,用isDirectory方法检验元素是否为目录,这样就把子目录数出来了。
做差就是文件的数量了。
哦,你是想继续数子目录的文件数量情况吗?那就再最外面套个递归。