【问题标题】:How could i append multiple json objects to the end of a json file我如何将多个 json 对象附加到 json 文件的末尾
【发布时间】:2019-10-15 21:52:05
【问题描述】:

我目前正在为我的计算机科学课完成一项大学作业,其中涉及在 java 中创建图书馆管理系统,我决定使用 JSON 对象来创建“书”,并将其写入文件。不过,我已经完成了这项工作,但成功有限,因为我对 java 比较陌生(尽管我确实对 c 有一些了解)。

问题出在“书”写入文件时,只能写入一次;如果我创建另一本书,它将覆盖另一本书。

我希望能够在文件中包含多本书,并且能够在不删除其他书籍的情况下添加书籍。

我看到有人与我有类似的问题,涉及使用 JSONArrays 和 JSONParser,但是在测试此代码后,我发现 JSONParser 不再存在或存储在 json 库中的其他位置。

我不确定我是否允许发布链接(如果我不允许,请让我删除它),但这里是那个人的问题的链接和提供的解决方案:

How to append data on a existing Json file using Java?

以下是相关代码: 请询问是否还有其他可以帮助找到解决方案的方法。我也可能无法立即回复,但如果有什么有效或无效,我会告诉你。

    // Main Stuff
    //Book creation
    JSONObject book = new JSONObject(); // make a new book using JSON
        book.put("Book title", bookname); // set book title
        book.put("Book Author", bookAuthor); // set book author
        book.put("ISBN", booknum); // set isbn

    String ReadableBooks = book.toString(); // Converts the json object to a string

       try (FileWriter file = new FileWriter(bookFile)) { // creates file...
            file.write(ReadableBooks); //writes data to file
            file.flush(); // clean up after ourselves
            file.close(); // close the file stream

        } catch (IOException e) { // except if there was an error
            System.out.println("Could net create file, printing stack trace...\n");
            e.printStackTrace(); // print where the error occurred
        }

【问题讨论】:

  • 您似乎想将JSON 文件视为数据库。这不是一个好主意,您应该使用SQL 数据库、List of In-Memory DatabasesNOSQLNoSQL Options for Java Developers。如果您只需要添加、搜索、列出功能,您甚至可以使用CSV 格式,它允许您将新书作为新行添加到文件中。要使用JSON,您需要阅读整个文件,添加新书并将其写回。您当然可以手动使用IO,但这听起来有问题。
  • 如果你真的想使用JSON文件来存放书籍,尝试使用Jackson图书馆。这里有一些相关的问题:Not able to java update json file using java jackson,Jackson API: partially update a string
  • 感谢您的回复,我目前正在研究您推荐的替代方案,并且可以看到肯定有比 json 更好的替代方案,即 csv 似乎非常适合。

标签: java json


【解决方案1】:

将代码更改为如下 sn-p。

FileWriter fileWriter = new FileWriter(bookFile,true);

java.io.FileWriter提供如下方法。

public FileWriter(@NotNull java.io.File file,
                      boolean append) throws java.io.IOException

正如您在 java 文档中看到的那样,Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
参数:
file – 要写入的 File 对象
append - 如果为真,那么字节将被写入文件的末尾而不是开头

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2020-04-12
    • 1970-01-01
    • 2016-08-21
    • 2017-06-15
    • 2016-03-31
    相关资源
    最近更新 更多