1 import java.io.*; 2 import java.util.*; 3 import javax.print.DocFlavor; 4 import javax.swing.*; 5 6 7 8 public class Main { 9 public static Map<String, Integer>map=new HashMap<>(); 10 public static void main(String[] args) { 11 Scanner sc=new Scanner(System.in); 12 System.out.println("请输入目录路径:"); 13 String path=sc.next(); 14 File di=new File(path); 15 dfs(di); 16 System.out.println("请输入n:"); 17 int n=sc.nextInt(); 18 List<Map.Entry<String,Integer>>list=new ArrayList<>(map.entrySet()); 19 list.sort(new Comparator<Map.Entry<String, Integer>>() { 20 @Override 21 public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { 22 return o2.getValue().compareTo(o1.getValue()); 23 } 24 }); 25 try(PrintWriter wirter=new PrintWriter ("cnt.txt")){ 26 int idx=0; 27 for(Map.Entry<String,Integer> mp:list){ 28 idx++; 29 if(idx==1)continue; 30 wirter.print(mp.getKey()); 31 wirter.print(' '); 32 wirter.print(mp.getValue()); 33 wirter.println(); 34 if(idx==n+1)break; 35 } 36 } 37 catch (FileNotFoundException e){ 38 e.printStackTrace(); 39 } 40 41 } 42 public static void dfs(File di){ 43 if(!di.exists()||!di.isDirectory()){ 44 return; 45 } 46 File[] files=di.listFiles(); 47 for(File file:files){ 48 if(file.isFile()){ 49 try (Scanner scanner = new Scanner(new BufferedReader(new FileReader( 50 file.getAbsoluteFile())));) { 51 scanner.useDelimiter("[,| |.|?|!|-]"); 52 while (scanner.hasNext()) { 53 String s= scanner.next(); 54 boolean f=false; 55 for(int i=0;i<s.length();i++){ 56 if(s.charAt(i)<'a'||s.charAt(i)>'z'){ 57 f=true;break; 58 } 59 } 60 if(f)continue; 61 if(map.containsKey(s))map.put(s,map.get(s)+1); 62 else map.put(s,1); 63 } 64 } catch (FileNotFoundException e) { 65 66 e.printStackTrace(); 67 } 68 }else if(file.isDirectory()){ 69 dfs(file); 70 } 71 } 72 } 73 }
标签:map,测试,di,File,file,new,课堂,public From: https://www.cnblogs.com/litianyu1969/p/17783350.html