gpt4 book ai didi

java - 从 hashmap 写入 txt 文件

转载 作者:搜寻专家 更新时间:2023-11-01 01:44:32 24 4
gpt4 key购买 nike

我有一个 Integer,String (K,V) 的 hashMap 并且只想将字符串值写入文件(而不是键 Integer)并且我只想将一些第 n 个条目(无特定顺序)写入文件而不是整个 map 。我试过很多次环顾四周,但找不到将第一个 n 条目写入文件的方法。(有一些例子,我可以将值转换为字符串数组,然后执行] 但它没有提供正确的格式我想写文件)

最佳答案

这听起来像是家庭作业。

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

关于java - 从 hashmap 写入 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15413467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com