1
这是我的问题:我需要将Interator写入文件“random.txt”我能够看到所有数据。数据是Store所在的地方,我可以用System.out.print看到它,但我的文件是空白的。我能够创建文件,但不能写入它。迭代器写入File.txt Java
我正在阅读我的文件。存储在树形图中并尝试写入文本文件。 (我可以用Array来处理,没有问题)但是这个带迭代器的Map弹起了我的脑袋。
如果有人能帮我一个垃圾,我会感激。
我需要使用TreeMap和迭代器。
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.");
}
完美谢谢你。那是两行代码的72小时头部急救。 – user1819551
哈哈哈......难道你不希望你的IDE警告你:“嘿,伙计,你没有冲洗和关闭!”?很高兴我能帮上忙 :) – ADTC