从hashmap写入txt文件

mag*_*443 4 java hashmap filewriter bufferedreader

我有一个整数,字符串(K,V)的hashMap,并且只想将字符串值写入文件(而不是键整数),我只想写一些第一个n条目(没有特定的顺序)到文件而不是整个地图.我已经尝试过四处寻找,但是找不到写入第一个n条目的方法.(有些例子我可以将值转换为字符串数组然后再进行操作]但是它没有提供正确的格式我要写的文件)

AWT*_*AWT 8

这听起来像是家庭作业.

public static void main(String[] args) throws IOException {
    // first, let's build your hashmap and populate it
    HashMap<Integer, String> map = new HashMap<Integer, String>();
    map.put(1, "Value1");
    map.put(2, "Value2");
    map.put(3, "Value3");
    map.put(4, "Value4");
    map.put(5, "Value5");

    // then, define how many records we want to print to the file
    int recordsToPrint = 3;

    FileWriter fstream;
    BufferedWriter out;

    // create your filewriter and bufferedreader
    fstream = new FileWriter("values.txt");
    out = new BufferedWriter(fstream);

    // initialize the record count
    int count = 0;

    // create your iterator for your map
    Iterator<Entry<Integer, String>> it = map.entrySet().iterator();

    // then use the iterator to loop through the map, stopping when we reach the
    // last record in the map or when we have printed enough records
    while (it.hasNext() && count < recordsToPrint) {

        // the key/value pair is stored here in pairs
        Map.Entry<Integer, String> pairs = it.next();
        System.out.println("Value is " + pairs.getValue());

        // since you only want the value, we only care about pairs.getValue(), which is written to out
        out.write(pairs.getValue() + "\n");

        // increment the record count once we have printed to the file
        count++;
    }
    // lastly, close the file and end
    out.close();
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,也许其他人会发现它在研究真正的问题时很有用.编写代码比在提问者试图确定*为什么*需要代码时来回嬉戏更容易.我向SO纯粹主义者道歉.:) (4认同)
  • 尽管如此,我还是添加了一些评论来解释循环中发生了什么.它比未注释的代码块更有用. (4认同)
  • 好吧,这不是我的功课,但它对我来说非常清楚和有帮助.+1 (2认同)