package test; import java.io.File; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; public class readIO1 { static int num=0,a=0; static String word[]=new String[1000000]; static int wordnum[]=new int[1000000]; public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.println("请输入要显示的单词个数:"); int sum=in.nextInt(); try{ String path = "C:\\Users\\lenovo\\Desktop\\Harry Potter and the Sorcerer's Stone.txt"; File file = new File(path); InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); BufferedReader br = new BufferedReader(new FileReader(file)); File file2 = new File("Test1.txt"); file2.createNewFile(); BufferedWriter out = new BufferedWriter(new FileWriter(file2)); String s=""; s=br.readLine(); while(s!=null) { s=s.toLowerCase();// 大写转小写 StringTokenizer st = new StringTokenizer(s," ".,?;! :“”‘: "); while(st.hasMoreElements()) { String str =(String)st.nextElement(); for(int j=0;j<num;j++) { if(str.equals(word[j])) { wordnum[j]++; }else a++; } if(a==num) { word[num]=str; wordnum[num]++; num++; } a=0; } s=br.readLine(); } for(int i=0;i<num;i++) { for(int j=i+1;j<num;j++) { if(wordnum[j]>wordnum[i]) { int temp=wordnum[i]; wordnum[i]=wordnum[j]; wordnum[j]=temp; String Temp=word[i]; word[i]=word[j]; word[j]=Temp; } } } for(int i=0;i<sum;i++) { System.out.println(word[i]+" "+wordnum[i]); } for(int i=0;i<word.length;i++) { out.write(i+":"+word[i]+" "); out.flush(); } out.close(); }catch(Exception e){ e.printStackTrace(); } } }
实验截图:
实验主要难在文件中单词的分割,将这个问题解决之后就可以将所读单词存入数组,将其统一变为小写,然后比较计数。