gpt4 book ai didi

java - 访问和操作Maven项目中的资源文件

转载 作者:行者123 更新时间:2023-11-30 06:31:04 24 4
gpt4 key购买 nike

我知道关于这个主题已经有很多问题,但似乎没有一个有帮助。在我的 Maven 项目中,我尝试访问 src/main/resource 文件,并且我知道在运行时,当我想要读取文件并写入文件时,我必须访问它的类路径或其他内容。

我真的不确定它是如何工作的,我设法编写了从文件中读取的代码,但我不知道如何编写写入文件的代码。这是我到目前为止所拥有的:

    private File userFile;
private ObjectMapper om;
private InputStream is;

public UserService() {
om = new ObjectMapper();

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
is = classLoader.getResourceAsStream("files/userJSON.json");

}

此构造函数代表 UserService 类,我使用它的方法来访问位于 userJSON.json 文件中的用户资源。这是我用来读取文件的方法:

public List<User> readJSON() throws JsonParseException, JsonMappingException, IOException{


BufferedReader br = new BufferedReader(new InputStreamReader(is));


List<User> list = om.readValue(br,new TypeReference<List<User>>(){});

return list;
}

我如何写入文件,如果可能的话请向我解释这是如何工作的。我的意思是 Maven 如何在运行时处理文件等等。

最佳答案

只需调用此方法,它就会读取文件并将其转换为 JSONObject:

private static JSONObject readUserJSON() throws FileNotFoundException, IOException, ParseException {
String jarPath = (new File("")).getAbsolutePath();
JSONObject config = null;
JSONParser parser = new JSONParser();
config = (JSONObject) parser.parse(new FileReader(jarPath + "resource/files/userJSON.json"));

return config;

}

在 .pom 文件中添加此依赖项:

        <dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple example</artifactId>
<version>1.1.1</version>
</dependency>

使用下面的语句,您可以获得文件的绝对路径,并且可以使用文件编写器写入它:

String jarPath = (new File("")).getAbsolutePath();

关于java - 访问和操作Maven项目中的资源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46114248/

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