0

我正在阅读一个文件并希望将文件存储到某些单词,在这个例子中“是”到 aHashMap of < Integer, document >.但我被困住了HashMap,这是我的思路。

BufferedReader in = new BufferedReader(new FileReader("filename.txt"));  
String line;     
int i = 0;
     while ((line = in.readLine()) != null) {  
       if (!line.startwith("yes");{
         //add line to hashMap[i]
         i++;
        }

  System.out.println(hashMap[i]);  
}  

如何在“是”之前添加我的文本HashMap

4

3 回答 3

1

您使用 HashMap 存储具有唯一键的键、值对。

你当然可以在某事上分道扬镳:

split_line = line.split(delimiter);

并存储:

\** I am being unsafe here. You should probably check for null and type. *\
hashmap.put( new Integer(split_line[0]), split_line[1]);

但这是你想做的吗?

于 2012-08-08T05:52:27.620 回答
0

我真的不明白你想在 HashMap 中存储什么。你能更具体一点吗?

这是使用Scanner的方法 - 我更喜欢它,而不是简单地逐行解析。

public class Main {
public static void main(String[] args) throws FileNotFoundException {
    StringBuilder responseBuilder = new StringBuilder();
    File file = new File("/Users/eugene/Desktop/MyFile.txt");
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter("yes");
    while(scanner.hasNext()){
        responseBuilder.append(scanner.next());
        break;   
    }
    System.out.println(responseBuilder.toString());
}

}

于 2012-08-08T06:02:37.217 回答
0

如果您在 Map 中的键是整数,其值从 0 到 n,那么您不需要 map 而需要 List。

 List<String> goodWords = new ArrayList<String>();
 while ((line = in.readLine()) != null) {  
       String[] words = line.split(" ");
       for (String str : words) {
           if (!"yes".equals(str)) {
               goodWords.add(str);
           }
       }
 }
于 2012-08-08T05:57:17.883 回答