Java FileWriter 帮助

发布于 2024-07-25 12:23:24 字数 458 浏览 5 评论 0原文

好吧...所以我有一个相当有趣的错误...我声明了一个名为 file 的 FileWriter,并且让它经历以下 for 循环:

for (int i = 0; i < a.radtot; i++) {
    file.write("" + i * a.rstep);

    for (int n = 0; n < a.timetot; n++) {
        file.write("\t " + T[n][i]);
        System.out.println(T[n][i] + " " + n + " " + i);
    }

    file.write("\n");
}

最后,System.out.println 命令打印我期望的内容到,但文件中途中断...就像,不是打印出 System.out 所做的所有内容...它停在中间。 有谁知道为什么会这样做? 难道我做错了什么?

Okay... so I have a fairly interesting error... I declare a FileWriter called file, and I have it go through the following for loops:

for (int i = 0; i < a.radtot; i++) {
    file.write("" + i * a.rstep);

    for (int n = 0; n < a.timetot; n++) {
        file.write("\t " + T[n][i]);
        System.out.println(T[n][i] + " " + n + " " + i);
    }

    file.write("\n");
}

At the end of it, the System.out.println command prints what I expect it to, but the file cuts off midway... As in, instead of printing out everything System.out does... it stops in the middle. Does anyone happen to know why it would do that? Am I doing something wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情仇皆在手 2024-08-01 12:23:24

您需要调用 close完成后,在 FileWriter 上单击 () 。 这会强制所有输出实际写入磁盘(否则可能会留在缓冲区中)。

for (int i = 0; i < a.radtot; i++) {
    file.write("" + i * a.rstep);

    for (int n = 0; n < a.timetot; n++) {
        file.write("\t " + T[n][i]);
        System.out.println(T[n][i] + " " + n + " " + i);
    }

    file.write("\n");
}
file.close(); // <-- Add this

(为了简洁起见,我假设您省略了异常处理,所以我也做了同样的事情。close() 通常位于 finally 块中,以确保它会一直运行。)

You need to call close() on the FileWriter when you're done with it. This forces all output to be actually written to disk (it could be left in a buffer otherwise).

for (int i = 0; i < a.radtot; i++) {
    file.write("" + i * a.rstep);

    for (int n = 0; n < a.timetot; n++) {
        file.write("\t " + T[n][i]);
        System.out.println(T[n][i] + " " + n + " " + i);
    }

    file.write("\n");
}
file.close(); // <-- Add this

(I'm assuming you've omitted exception handling for brevity, so I have done the same. The close() would ordinarily be in a finally block to ensure that it will always run.)

风吹雪碎 2024-08-01 12:23:24

尝试添加:

file.close();

close() 方法描述如下:

关闭流,首先刷新它。

Try adding:

file.close();

The close() method description says:

Closes the stream, flushing it first.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文