Here is my issue: I need to write the Interator to the file "random.txt" I am able to see all the data. The data is Store where suppose to, I can see it with the System.out.print but my file is in blank. 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. ( I am able to doit with Array with not problem) But this Map with Iterator is bouncing my head.
If some one can help me a litter I will appreciated.
I need to use the TreeMap and the 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:
out.flush();
out.close();
Short explanation: BufferedWriter
buffers in memory what you write. It doesn't immediately write to file when you call the write
method. 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. And finally you should always close
the BufferedWriter that will no longer be used, to avoid memory leaks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.