简体   繁体   English

从hashmap写入txt文件

[英]Writing from hashmap to a txt file

I have a hashMap of Integer,String (K,V) and want to write only the string values to a file (not the key Integer) and I want to write only some 1st n entries (no specific order) to the file and not the entire map. 我有一个整数,字符串(K,V)的hashMap,并且只想将字符串值写入文件(而不是键整数),我想只写一些第一个n条目(没有特定的顺序)到文件而不是整个地图。 I have tried looking around a lot but could not find a way to write 1st n entries to file.(There are examples where I can convert the value to array of Strings and then do it] but then it does not provide the correct format in which I want to write the file) 我已经尝试过四处寻找,但是找不到写入第一个n条目的方法。(有些例子我可以将值转换为字符串数组然后再进行操作]但是它没有提供正确的格式我要写的文件)

This sounds like homework. 这听起来像是家庭作业。

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();
}

Just the flow ... 只是流动......

Get the iterator for values. 获取值的迭代器。 Iterate through them incrementing the counter. 通过它们迭代递增计数器。 Come out when the counter reaches n entries. 当计数器达到n个条目时出来。

Other approach is to use 其他方法是使用

for(int i=0, max=hashmap.size(); i<max, i<n; i++) { ... }

Reference: Java API 参考: Java API

Try this 试试这个

  1. Get the collection of values from the map. 从地图中获取值集合。 Read the Map object reference and find the method named values . 读取Map对象引用并找到名为values的方法。 Use this method 使用此方法
  2. Iterate over the collection of values that you retrieved in step 1. Write some (of your choosing) to a file. 迭代在步骤1中检索到的值集合。将一些(您选择的)写入文件。 Format as desired while writing. 写入时根据需要格式化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM