这是我的问题:我需要将 Interator 写入文件“random.txt”,我才能看到所有数据。数据存储在应该存储的位置,我可以使用 System.out.print 看到它,但我的文件是空白的。我可以创建该文件,但不能写入该文件。
我正在从我的 comp 中读取一个文件。存储在树状图中并尝试写入文本文件。 (我可以用数组来做,没有问题)但是这个带有迭代器的映射让我头疼。
如果有人可以帮助我一窝,我将不胜感激。
我需要使用 TreeMap 和 Iterator。
public static void main(String[] args) throws FileNotFoundException, IOException {
Map<String, String> Store = new TreeMap<>();
Scanner text=new Scanner(System.in);
System.out.println("enter file: ");
//C:\Users\Alex\Desktop\Fruits\fruits.txt
String rap=text.next();
File into = new File(rap);
try (Scanner in = new Scanner(into)) {
while (in.hasNext()){
String name=in.next();
String fruta = in.next();
Integer num= Integer.parseInt(in.next());
System.out.println(fruta+"\t"+name+"\t"+num);
if (Store.containsKey(fruta)){
Store.put(name,Store.get(name)+fruta );
}
else{
Store.put(name,fruta);
}
}
in.close();
}
System.out.println();
// insert data to store MAP
Set top=Store.entrySet();
Iterator it = top.iterator();
// debugging
System.out.println(top);
// Creating file???????
FileWriter fstream = new FileWriter("random.txt");
//identify File to be write??????
BufferedWriter out = new BufferedWriter(fstream);
//iterator Loop
while(it.hasNext()) {
Map.Entry m = (Map.Entry)it.next();
String key = (String)m.getKey();
String value = (String)m.getValue();
//writing to file?????
out.write("\t "+key+"\t "+value);
// debugging
System.out.println(key +"\t"+ value);
}
System.out.println("File created successfully.");
}
最佳答案
完成 while
循环(写入文件的循环)后,执行以下操作:
out.flush();
out.close();
简短说明: BufferedWriter
在内存中缓冲您写入的内容。当您调用 write
方法时,它不会立即写入文件。一旦 while 循环完成并且要写入文件的数据已在缓冲区内存中准备好,您应该调用 flush
来执行实际写入硬盘的操作。最后,您应该始终关闭
不再使用的 BufferedWriter,以避免内存泄漏。
关于java - 写入 File.txt Java 的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13353608/