正如標題所述,我試圖讀取一個簡單的文本文件並將單個單詞提交到哈希映射中。我最終將構建我的程序計數頻率每個字,其中包含HashMap我有以下的文本文件(的text.txt):Java - 將.txt文件中的單詞放入HashMap中?
it was the best of times
it was the worst of times
it was the age of wisdom
it was the age of foolishness
it was the epoch of belief
it was the epoch of incredulity
it was the season of light
it was the season of darkness
it was the spring of hope
it was the winter of despair
see the test
try this one
我已經寫了下面的C
import java.util.*;
import java.io.*;
public class Profile{
public static String file;
public static int len;
public static int count = 0;
public static String[] words;
public static String[] unrepeatedWords;
public static Map<String, Integer> record = new HashMap<String, Integer>();
//Integer count = record.get(word);
//Integer count = record.get(word);
Set<String> keySet = record.keySet();
//Method to read whole file
static void wholeFile(File file){
try {
Scanner in = new Scanner(file);
int lineNumber = 1;
while(in.hasNextLine()){
String line = in.nextLine();
//count += new StringTokenizer(line, " ,").countTokens();
//System.out.println(line);
words = line.split("/t");
words = line.split(" ");
//System.out.println(words + "");
lineNumber++;
}
for(String word : words){
//System.out.println(word);
if(!record.containsKey(word)){ record.put(word, 1); }
if(record.containsKey(word)){ record.put(word, record.get(word) + 1); }
}
System.out.println(record);
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Profile(String file){
this.file = file;
}
Profile(String file, int len){
this.file = file;
this.len = len;
}
public static void main(String[] args){
file = args[0] + "";
File a = new File(file);
//Scanner in = new Scanner(a);
wholeFile(a);
}
}
然而,當我運行命令運行配置文件text.txt,我只存儲到HashMap的最後一行:
> run Profile text.txt
{one=2, this=2, try=2}
>
我做錯了什麼?如何有效地存儲HashMap中的.txt文件中的所有單詞?任何建議都會有幫助。
我建議使用調試器或添加一些'System.out.println'行來查看是否可以關注發生的事情 - 只有2個小錯誤。 –