首页 > 解决方案 > 杰克逊 writeValue() 到文件不使用相对路径

问题描述

我正在尝试通过杰克逊将对象写入 json 文件。

如果我提供一个绝对路径"D:/Projects/quiz-red/src/main/resources/com/models/Quizzes.json"它正在工作并且文件出现在目录中

但是,如果我提供相对路径 -"/com/models/Quizzes.json"我只是进入Process finished with exit code 0控制台,没有任何反应。我究竟做错了什么?

有我的代码:

public static void writeEntityToJson(Object jsonDataObject, String path) throws IOException {
        ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
        writer.writeValue(new File(path), jsonDataObject);
    }

   public static void main(String[] args) throws IOException {

        Quiz quiz = new Quiz(5L, "Title", "Short desc");

        writeEntityToJson(quiz, "/com/models/Quizzes2.json");
    }

我想使用相对路径将文件保存到 DataProvider 中的资源

在此处输入图像描述

例外:

Exception in thread "main" java.io.FileNotFoundException: com\models\Quizzes5.json (The system cannot find the path specified)
    at java.base/java.io.FileOutputStream.open0(Native Method)
    at java.base/java.io.FileOutputStream.open(FileOutputStream.java:298)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:237)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:187)
    at com.fasterxml.jackson.core.JsonFactory.createGenerator(JsonFactory.java:1223)
    at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:942)
    at com.utils.DataProvider.writeEntityToJson(DataProvider.java:33)
    at com.utils.DataProvider.main(DataProvider.java:50)

标签: javajsonfileiojackson

解决方案


推荐阅读