簡體   English   中英

迭代器寫入File.txt Java

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM