从hashmap写入一个txt文件
我有一个整数,字符串(K,V)的哈希映射,并希望只写入字符串值到一个文件(而不是键整数),我想只写一些第n个条目(没有特定的顺序),而不是整个地图。 我已经尝试过四处寻找,但找不到写第1个条目到文件的方法(有些例子中我可以将值转换为字符串数组然后执行)但是它不提供正确的格式在其中我想写文件)从hashmap写入一个txt文件
这听起来像功课。
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();
}
是的,也许别人会发现它在研究一个真正的问题时很有用。编写代码比直接与提问者反复试图确定*为什么需要代码更容易。我对SO纯粹主义者表示歉意。 :) – AWT 2013-03-14 16:04:34
它最好你解释你的代码,没有解释这段代码是毫无价值的。正如你所说,如果他们明白的话,这对其他人会有用。没有解释他们可以简单地复制/粘贴。 :) – PermGenError 2013-03-14 16:06:45
感谢兄弟......这不是硬件问题....我是新来的java和有点困惑的迭代器和计数器......上面解释了我需要 – mag443 2013-03-14 16:11:55
'那么它不提供我想要写入文件的正确格式'你说的这种格式是什么? – nattyddubbs 2013-03-14 15:33:38
我想打印字符串,因为它们是...每行1个...而不是列表[]的形式,即逗号分开 – mag443 2013-03-14 15:50:29