我有一个整数,字符串(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
- 1. 如何从一个txt文件导入raw_input /将raw_input写入一个txt文件
- 2. 读取和写入一个txt文件
- 3. 写入一个txt文件在c#
- 4. 在pythonanywhere中写入一个txt文件?
- 5. 写入TXT文件?
- 6. 从HTML输入中写入.txt文件
- 7. 从.txt文件中读取和写入.txt文件
- 8. 从右到左写入一个txt文件
- 9. Java将多个HashMap写入文件
- 10. 从txt文件读取和写入
- 11. 从JAR读取/写入.txt文件
- 12. 从txt文件读取并写入HBase
- 13. Node.js将一行写入.txt文件
- 14. Buffered Writer写入.txt文件
- 15. 写入到txt文件java
- 16. 将RegEx写入txt文件
- 17. 用Python写入txt文件
- 18. VB.Net写入Txt文件
- 19. 将NSMutableArray写入txt文件
- 20. 写入.txt文件onclick
- 21. 在txt文件中写入
- 22. FileWriter不写入.txt文件
- 23. hashmap和多个txt文件java
- 24. 使用批处理文件中写入TXT另一个文件
- 25. 如何将一个JTable的内容写入一个txt文件
- 26. 在一个类中循环并写入一个txt文件
- 27. 要从一个txt文件
- 28. 要从一个txt文件
- 29. 从文本文件读入一个类中的对象 - 在另一个txt文件中写入
- 30. 将文件路径写入.txt文件
'那么它不提供我想要写入文件的正确格式'你说的这种格式是什么? – nattyddubbs 2013-03-14 15:33:38
我想打印字符串,因为它们是...每行1个...而不是列表[]的形式,即逗号分开 – mag443 2013-03-14 15:50:29