使用 filewriter 在 for 循环中附加到 csv

发布于 2025-01-14 12:35:04 字数 1254 浏览 3 评论 0原文

我正在事件驱动的 java 应用程序中调试 csv 输出。我在 init 上这样定义我的文件写入器。

    public File csvFile;
    public FileWriter fileWriter;

然后我初始化它们,

 this.csvFile = new File("c:\\missingitems.csv");
    this.fileWriter = null;
    try {
        this.fileWriter = new FileWriter(this.csvFile);
        StringBuilder line = new StringBuilder();
        line.append("Date, ItemId");
        line.append("\n");
        this.fileWriter.write(line.toString());

    } catch (IOException e) {
        e.printStackTrace();
    } 

数据中的每个时间步都会调用它们

for(Long item : this.items) {
            StringBuilder line = new StringBuilder();
            line.append(event.getDateTime().toLocalDate().toString() + "," +item.intValue());
            line.append("\n");
            try {
                this.fileWriter.write(line.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

然后在我的实际程序逻辑中,在我调用的程序退出时

        try {
        this.fileWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

,但是这似乎只有在我在每次追加后关闭文件编写器时才起作用。有没有办法保持文件打开并仅附加到它,我也希望在应用程序崩溃时不会丢失我的数据。我是一个Python爱好者,对java不太熟悉。

I am working on a debuging csv output inside an event driven java application. I define my filewriter like this on init.

    public File csvFile;
    public FileWriter fileWriter;

then I initialies them

 this.csvFile = new File("c:\\missingitems.csv");
    this.fileWriter = null;
    try {
        this.fileWriter = new FileWriter(this.csvFile);
        StringBuilder line = new StringBuilder();
        line.append("Date, ItemId");
        line.append("\n");
        this.fileWriter.write(line.toString());

    } catch (IOException e) {
        e.printStackTrace();
    } 

then within my actual program logic this gets called for every timestep in my data

for(Long item : this.items) {
            StringBuilder line = new StringBuilder();
            line.append(event.getDateTime().toLocalDate().toString() + "," +item.intValue());
            line.append("\n");
            try {
                this.fileWriter.write(line.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

on exit of my program I call

        try {
        this.fileWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

However this seems to be only working if i close the filewriter after each append. Is there a way of keeping the file open and just append to it, I would also like to not loose my data in case my application crashes. I am a python guy and not super familiar with java.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文