簡體   English   中英

我如何在 Java 文件中寫入?

[英]How can i write in a Java File?

我想寫一個文件,但我遇到了一個非常奇怪的問題。 如果我這樣寫代碼:

BufferedWriter bw = new BufferedWriter(new FileWriter(nom + ".txt"));
        String s = "";
        for (int i = 0; i < DIMENSIO; i++) {
            for (int j = 0; j < DIMENSIO; j++) {
                s +=tauler.isBomba(i,j);
                s += '\n';
                s +=tauler.isSeleccionat(i,j);
                s += '\n';
            }
        }
        bw.write(s);

該文件是空的,但是如果我以這種方式編寫代碼:

BufferedWriter bw = new BufferedWriter(new FileWriter(nom + ".txt"));
        String s = "";
        for (int i = 0; i < DIMENSIO; i++) {
            for (int j = 0; j < DIMENSIO; j++) {
                s +=tauler.isBomba(i,j);
                s += '\n';
                s +=tauler.isSeleccionat(i,j);
                s += '\n';
                bw.write(s);
            }
        }

有用。 問題是第二種方式不正確,因為我需要在 for 之后編寫它。

最后需要關閉BufferedWriter object。

bw.close();

這會導致數據從 stream 中刷新到文件中。 我認為它在循環內起作用的原因是它定期刷新數據。

但是,正如 Clashsoft 所建議的,更好的編寫方法是使用try-with-resource語句,它會自動處理關閉BufferedWriter

try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
    // do your logic here
    writer.write(str);

    // once control leaves this block, the writer gets closed automatically
}
catch(IOException e){
    // handle the exception
}

調用 bw.write(s) 后嘗試使用bw.close() bw.write(s);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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