java - Spring Boot jar 保存到现有文件

标签 java spring spring-boot jackson fileoutputstream

我想用 jackson 将数据保存到现有文件(更新它),但当我从 jar 运行我的项目时它不起作用。

我需要使用 json 作为“数据库”(我知道这很愚蠢,但这是一个学校项目),为此,我在执行任何 CRUD 操作时加载并保存所有数据。当我使用 IDE 运行它时,它工作正常,但是当我尝试将其作为 jar 时,它在从 ClassPathResource 读取文件时出现问题。

所以我有这个方法来保存对文件的更改:

private List<Item> items;
private ObjectMapper mapper;
private ObjectWriter writer;

public void saveData() {
        mapper = new ObjectMapper();
        writer = mapper.writer(new DefaultPrettyPrinter());
        try {
            writer.writeValue(new ClassPathResource("items.json").getFile(), items);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

当我通过 IntelliJ 运行它时,它工作得很好,但当我将它作为 jar 运行时,它就不起作用了。 我找到了使用 this question 中的 InputStream 加载数据的解决方案方法如下:

public void loadData() {
        mapper = new ObjectMapper();
        try {
            ClassPathResource classPathResource = new ClassPathResource("items.json");

            InputStream inputStream = classPathResource.getInputStream();
            File tempFile = File.createTempFile("test", ".json");

                FileUtils.copyInputStreamToFile(inputStream, tempFile);

            System.out.println(tempFile);
            System.out.println(ItemDao.class.getProtectionDomain().getCodeSource().getLocation().getPath().toString());
            items = mapper.readValue(tempFile, new TypeReference<List<Item>>() {
            });
        } catch (IOException e) {
            items = null;
            e.printStackTrace();
        }
    }

但我仍然不知道如何实际保存更改。我正在考虑使用 FileOutputStream 但我一无所获。

所以我希望在 jar 文件中实现此功能,并能够将更改保存到同一文件,提前感谢您的帮助!

最佳答案

当您想要进行读/写操作时,最好将文件保留在项目之外。运行 jar 时,传递文件名和路径作为参数。比如 -DfileName=/Users/chappa/Documents/items.json 等。这样,你就拥有了绝对路径,并且可以对其执行读/写操作

如果您使用的是java 1.7或以上版本,请使用以下方法写入数据。 要读取数据,可以使用jackson api按原样加载json文件。

Path wipPath = Paths.get("/Users/chappa/Documents/items.json");
try (BufferedWriter writer = Files.newBufferedWriter(wipPath)) {
            for (String record : nosRecords) {
                writer.write(record);
            }
        }

如果你想使用IO流读取json,你可以使用下面的代码

        Path wipPath = Paths.get("/Users/chappa/Documents/items.json");
        try (BufferedReader reader = Files.newBufferedReader(wipPath)) {
            String line=null;
            while((line = reader.readLine()) != null) {
                    System.out.println(line);
            }
        }

关于java - Spring Boot jar 保存到现有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228805/

相关文章:

java - 使用 getOrDefault() 时,我没有获得默认值

java - 当我的 session 创建策略设置为 STATELESS 时,为什么 Spring Security 的 SessionManagementFilter 仍在运行?

spring-boot - Spring 计划的 cron 作业运行次数过多

java - 当我为同一个 .java 文件构建多次生成的项目 .class 文件时

c# - C# 中的无符号右移对负数使用 Java 语义

Java - 无需在代码中指定用户名和密码即可连接到 MySQL

java - Android Studio : Failed to resolve: com. google.android.gms :play-services:fp9. 0.0

java - Websocket(spring)ssl连接(空链)

spring - Camel动态构建处理器bean调用

java - Spring Boot 应用程序无法热插拔更改