【问题标题】:I have a program that should write some data to a file, it does not and I have no idea why [duplicate]我有一个程序应该将一些数据写入文件,但它没有,我不知道为什么[重复]
【发布时间】:2013-01-07 16:56:00
【问题描述】:

我有一个简单的程序,需要使用FileWriterBufferedWriter 将几行字符串写入文件。它已经从文件中读取了(在这种情况下)完全相同的数据,并将其存储在运行时内存中,但它完全拒绝写入它,我不知道为什么。通常我会尝试调试它并查看发生了什么,但我不知道我在寻找什么。

这是我的代码:

public void close () {
    FileWriter output = null;
    BufferedWriter fileOut = null;

    // I use the exact same method to read from file so this should work
    // this.prajituri :: ArrayList
    // toString is @Override

    try {
        output = new FileWriter(this.fileName);
        fileOut = new BufferedWriter(output);

        for (int i = 0; i < this.prajituri.size(); i++) {
            fileOut.write(prajituri.get(i).toString());
            System.out.println(prajituri.get(i).toString());
            fileOut.newLine();
        }
    } catch (IOException ioe) {
        System.out.println("Output error: " + ioe);
    } finally {
        if (fileOut != null)
            fileOut = null;
        if (output != null)
            output = null;
    }
}

以防万一,这是我的 toString:

@Override
public String toString () {
    return this.name + ";" + this.weight + ";" + this.price;
}

每次我尝试写入文件时,它都会给我一个空文件。我是不是做错了什么?

我检查了,this.prajituri 实际上很好(拥有它应该拥有的所有数据) 我使用System.out.println(prajituri.get(i).toString()) 来检查它应该 写什么,这也可以。然而它什么也没写。

【问题讨论】:

  • if (fileOut != null) fileOut.close; 而不是fileOut = null;

标签: java file-io


【解决方案1】:

你必须关闭你的 BufferedWriter fileOut.close()

【讨论】:

  • +1,虽然您也可以将其刷新并让系统为您关闭它,但这应该可以解决问题。
  • @corsiKa - 系统不会为您关闭它,如果您不明确调用 close,您最终会出现文件句柄泄漏。
  • @GanGnaMStYleOverFlowErroR 哦,对。谢谢!
  • @Paolo 我不应该在早上喝咖啡之前做 cmets。你是绝对正确的。它会为您关闭它的唯一时间是流程结束时,这并不是一个很好的做法......
【解决方案2】:

立即写入磁盘:

output.flush();

完成后:

output.close();

close( ) 包括flush( )

【讨论】:

  • 那么我不需要刷新之前我写,是吗?
  • 没有。写入保存在缓冲区中。刷新强制缓冲区到磁盘。
【解决方案3】:

您需要刷新流以将其写入磁盘。

flush in java.io.FileWriter

您应该通过调用fileout.close()(无论如何都会在内部调用flush)来正确关闭流。

【讨论】:

    【解决方案4】:

    您必须刷新/关闭您的流。如果您使用的是 Java SE 7,最简单的方法是使用新的自动资源管理功能:

    http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-14
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多