正如标题所述,我试图读取一个简单的文本文件并将单个单词提交到哈希映射中。我最终将构建我的程序计数频率每个字,其中包含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个小错误。 –