PrintWriter creates file but doesn't write [duplicate]

老子叫甜甜 提交于 2020-12-12 17:46:53

问题


I used the example code on a website somewhere and it looks like this:

package gdt.enlightening;

import notify.*;
import javax.swing.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class export {
    public static void Export(String path) {

        try {
            // Package.json
            File file = new File(path + "/package.json");

            FileWriter pw = new FileWriter(file);
            pw.write("test");
            pw.write("Hi!");

            pw.write("    \"id\": \"" + main.packageID + "\",\r\n");
            pw.write("    \"name\": \"test\",");

            notify.Notify.info("GDT Enlightening", "Finished exporting without errors.");
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

It creates the file but leaves it completely empty. I do not seem to figure out why. Do I need a "File" object?

I've tried different solutions found on here but it doesn't work. I've also played around with the printing method.

EDIT: Fixed by calling pw.close() at the end


回答1:


You should add pw.close() to fix this problem.

Else that data will be lost in a buffer.



来源:https://stackoverflow.com/questions/25593147/printwriter-creates-file-but-doesnt-write

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!