有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java文件中编写?

我想写一个文件,但我有一个非常额外的问题。 如果我这样写代码:

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之后编写它


共 (2) 个答案

  1. # 1 楼答案

    在调用bw.write(s);之后尝试使用bw.close()

  2. # 2 楼答案

    最后需要关闭BufferedWriter对象

    bw.close();
    

    这会导致数据从流中清除到文件中。我认为它在循环中工作的原因是它定期刷新数据

    但是,正如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
    }