统计一个文件夹中出现次数最多的单词

统计一个文件夹中出现次数最多的单词

import java.io.*;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
//统计一个文件夹中出现次数最多的单词
public class FileTest {

    public static void test(String[] args) throws IOException {

        File  file = new File("C:\\Users\\zhangxiaocui\\Desktop\\word.txt");
        if(!file.exists()){
            System.out.println("doesn't exsit");
        }

        Scanner sc = new Scanner(file);
        Scanner sc1 = new Scanner(System.in);

        HashMap<String,Integer> hm = new HashMap<>();
        System.out.println("输出文件");
        int count=1;int max =0;
        while (sc.hasNextLine()){
            String line = sc.nextLine();
            String[] linewords = line.split("\\W+");
//            Set<String> wordset = hm.keySet();
            for(int i =0;i<linewords.length;i++){
                if(hm.containsKey(linewords[i])){
                    System.out.println(i+" :"+linewords[i]);
                    Integer number = hm.get(linewords[i]);
                    number++;
                    max=Math.max(number,max);
                    hm.put(linewords[i],number);
                }else{
                hm.put(linewords[i],1);}

            }
        }
        System.out.println("最多出現的次數為:"+max);
//
//        FileInputStream fis = new FileInputStream("learn_java/src/main/java/com/jd/javaseleart/stream/TestFileInputStream.java");
//        byte[] bbuf = new byte[1024];
//        int hashRead =0;
//        while ((hashRead = fis.read(bbuf))>0){
//            System.out.println(new String(bbuf,0,hashRead));
//
//        }
//        //流操作完之后一定要关闭
//        fis.close();

        }

}

 

posted on 2021-06-30 10:59  cStream  阅读(128)  评论(0)    收藏  举报