[英]Iterator writing to File.txt Java
这是我的问题:我需要将Interator写入文件“ random.txt”,我才能看到所有数据。 数据存储在假定的位置,我可以使用System.out.print看到它,但是我的文件为空白。 我可以创建文件,但不能写入文件。
我正在从我的伴奏中读取文件。 存储在Treemap中并尝试写入文本文件。 (我可以用Array做到这一点,没有问题)但是这张带有Iterator的Map令我头疼。
如果有人可以帮我乱扔垃圾,我将不胜感激。
我需要使用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
在内存中BufferedWriter
您所写的内容。 调用write
方法时,它不会立即写入文件。 一旦while循环完成并且要写入文件的数据已准备好在缓冲存储器中,您应该调用flush
进行实际的硬盘写入。 最后,您应该始终close
不再使用的BufferedWriter,以避免内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.