gpt4 book ai didi

java - 如何在资源目录中用java创建文件

转载 作者:行者123 更新时间:2023-11-29 04:25:30 26 4
gpt4 key购买 nike

我有一个 maven 项目,需要在 file.json 中写入 JSON 对象,它应该位于

源/主要/资源/

但在我需要检查文件是否存在之前。如果不是,则创建它。

public static void writeMenuJSon(String jsonParamIn) {
JsonParser parser = new JsonParser();
JsonObject modulJson = parser.parse(jsonParamIn).getAsJsonObject();

//TODO check if file exists and create file if not

code here ...


// write to file JSON object
try (Writer writer = new FileWriter("path to file")){

Gson gson = new GsonBuilder().create();
gson.toJson(modulJson, writer);

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

}

最佳答案

如果您在 src/main/resources 中创建动态文件,那就完全错了 这只会在您的开发环境中工作。当您使用 Jar 或 War 部署代码时,文件系统上不会有此目录。它将包含在 Jar/War 或其他包装中。

如果你理解了上面的内容,还想做。转到当前工作目录以创建文件,通常从 IDE 启动 Main 时的工作目录设置为项目的根目录,因此在以下位置创建文件

src/main/resources/foo.txt

会做的。或者,您可以从 IDE 启动器或在运行时使用

System.getProperty("user.dir");

关于java - 如何在资源目录中用java创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46590688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com