有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

无法在java中将Json输出写入文件

我试图将简单的JSON数据写入一个文件,但我的文件似乎是空白的。它什么也没写。当我在java控制台中打印输出时,它会显示正确

import org.json.simple.JSONObject;

JSONObject obj = new JSONObject();

obj.put("Phone Number:", "XXXXXXXXX");
obj.put("Fname:", "Mike");
obj.put("Lname:", "Miller");
obj.put("Street:", "101");

try {
    FileWriter file = new FileWriter("D:\\file1.json");
    file.write(obj.toJSONString());
}
catch (Exception e) {
    e.printStackTrace();
}

我在网上也看到了类似的代码。我遵循同样的方法,但仍然不确定它为什么不将输出写入文件


共 (4) 个答案

  1. # 1 楼答案

    在这里,您没有将数据刷新到文件中。这就是为什么数据不会写入文件。如果还希望将现有数据保留在文件中,请尝试附加。下面是将新数据附加到现有文件的更新代码

    import org.json.simple.JSONObject;
    
     JSONObject obj = new JSONObject();
    
     obj.put("Phone Number:","XXXXXXXXX");
     obj.put("Fname:","Mike");
     obj.put("Lname:","Miller");
     obj.put("Street:","101");
    
     try {
    
              FileWriter file = new FileWriter("D:\\file1.json", true); // true to append at the end of file.
               file.write(obj.toJSONString());
               file.flush()
    
                }catch (Exception E)
                {
                    E.printStackTrace();
    
                }finally{
                    file.close();
                }
           }
    
  2. # 2 楼答案

    这是最新的工作版本

    public static void main(String...strings) throws IOException{   
            FileWriter file = new FileWriter("C:\\file1.json");
            try {
                JSONObject obj = new JSONObject();
                obj.put("Phone Number:","XXXXXXXXX");
                obj.put("Fname:","Mike");
                obj.put("Lname:","Miller");
                obj.put("Street:","101");
                file.write(obj.toString());
    
            }catch (Exception E)
            {
                System.out.println(E);
                E.printStackTrace();
            }finally{
                file.close();
            }
        }
    
  3. # 3 楼答案

    当您使用任何文件类编写代码时,我的意思是要么将内容写入文件,要么从文件中读取,关闭流始终是最佳实践

    代码应该是这样的

    FileWriter file = new FileWriter("D:\\file1.json");
    
    file.write(obj.toJSONString());
    file.close();
    
  4. # 4 楼答案

    在调用flush之前,操作系统可能不会将数据写入硬件:

    public static void main(String[] args) throws Exception {
        JSONObject obj = new JSONObject();
    
        obj.put("Phone Number:","XXXXXXXXX");
        obj.put("Fname:","Mike");
        obj.put("Lname:","Miller");
        obj.put("Street:","101");
        FileWriter file = new FileWriter("D:\\file1.json");
        try {
            file.write(obj.toJSONString());
        }catch (Exception E) {
            E.printStackTrace();
        } finally {
            file.flush();
            file.close();
        }
    }