[英]Iterator writing to File.txt Java
Here is my issue: I need to write the Interator to the file "random.txt" I am able to see all the data. 这是我的问题:我需要将Interator写入文件“ random.txt”,我才能看到所有数据。 The data is Store where suppose to, I can see it with the System.out.print but my file is in blank.
数据存储在假定的位置,我可以使用System.out.print看到它,但是我的文件为空白。 I am able to create the file but not to writer to it.
我可以创建文件,但不能写入文件。
I am reading a file from my comp. 我正在从我的伴奏中读取文件。 store in the Treemap and trying to write to the text file.
存储在Treemap中并尝试写入文本文件。 ( I am able to doit with Array with not problem) But this Map with Iterator is bouncing my head.
(我可以用Array做到这一点,没有问题)但是这张带有Iterator的Map令我头疼。
If some one can help me a litter I will appreciated. 如果有人可以帮我乱扔垃圾,我将不胜感激。
I need to use the TreeMap and the Iterator. 我需要使用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.");
}
After your while
loop (the one writing to file) is finished, do: 在您的
while
循环(一次写入文件)完成之后,请执行以下操作:
out.flush();
out.close();
Short explanation: BufferedWriter
buffers in memory what you write. 简短说明:
BufferedWriter
在内存中BufferedWriter
您所写的内容。 It doesn't immediately write to file when you call the write
method. 调用
write
方法时,它不会立即写入文件。 Once the while loop is finished and the data to write to file is prepared in buffer memory, you should call flush
to do the actual writing to hard disk. 一旦while循环完成并且要写入文件的数据已准备好在缓冲存储器中,您应该调用
flush
进行实际的硬盘写入。 And finally you should always close
the BufferedWriter that will no longer be used, to avoid memory leaks. 最后,您应该始终
close
不再使用的BufferedWriter,以避免内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.