-1

我有下一个功能:

static void write()
{
    try {
         File file = new File ("flip.out");
         BufferedWriter out = new BufferedWriter(new FileWriter(file));
         out.write(sMax);
         System.out.println(sMax);//This command it works
         out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

问题是我的程序没有在我的文件中写入任何内容。

4

3 回答 3

1

有几件事要纠正 -

为什么要创建两个不同的 File 对象实例

File file = new File ("flip.out");
BufferedWriter out = new BufferedWriter(new FileWriter("flip.out"));

你需要做的就是

File file = new File ("flip.out");
BufferedWriter out = new BufferedWriter(new FileWriterfile(file ) ));

接下来把你的近距离通话finally statement而不是尝试阻止。为什么?由于 IOException 发生,资源不会被关闭,如果资源没有被关闭,您的更改可能不会反映在文件中。

接下来,不捕捉是一个很好的编程习惯Runtime exceptions。所以不要Exception用作多态类型来捕获您的异常。在您的情况下使用像 IOException 这样抛出的任何东西。

现在可能有各种原因说明为什么要在文件中写入注释。由于您没有得到和 Exception 这可能发生的原因之一,因为您的静态函数没有被调用或字符串/对象sMax(无论是什么)为空。

此外,文件(如果尚未存在)将在当前目录中创建。因此,如果有多个实例是您的代码在其中创建具有相同名称的文件,那么请确保您检查的是正确的。

于 2013-10-20T17:48:08.990 回答
0

out.flush()你能在关门前打电话吗?这将确保缓冲区中的任何内容立即写入文件。

于 2013-10-20T17:47:39.680 回答
0

您必须刷新流才能将内存中的内容写入驱动器。您写入 BufferedWriter 的内容位于一个字节数组中,等待其余部分被填满,然后再将其实际写入磁盘。这有助于提高性能,但意味着您必须刷新流,以防您没有填满该缓冲区。这是你如何做到的:

static void write() throws IOException {
    BufferedWriter out = new BufferedWriter(new FileWriter("flip.out"));
    try {
        out.write(sMax);
        out.flush();
    } catch (Exception e) {
        // probably could ditch this and 
        // just the exception bubble up and 
        // handle it higher up.
        e.printStackTrace(); 
    } finally {
        out.close();
    }
}

因此,如果它到达了 flush(),我们就知道我们将所有内容都写入了我们想要的流。但是,如果我们遇到异常,我们确保无论成功或异常都关闭流。最后,我们的流在 try 语句之外,因为 Writers/OutputStreams 在构造过程中抛出的唯一异常是 FileNotFoundException,这意味着文件一开始就没有被打开,所以我们不必关闭它。

于 2013-10-20T17:52:34.920 回答