java - 在 Spring boot fat jar 中读取文件

标签 java spring spring-boot jar

我们有一个 spring boot 应用程序,它有一个遗留的 jar api,我们使用它需要使用 InputFileStream 加载属性。我们将遗留 jar 包在我们的 spring boot fat jar 中,属性文件位于 BOOT-INF/classes 文件夹下。我可以看到 spring 正在加载所有相关的属性,但是当我将属性文件名传递给遗留 jar 时,它无法读取属性文件作为它在 jar 内部并且不在物理路径下。在这种情况下,我们如何将属性文件传递给旧 jar?

请注意,我们无法更改旧 jar。

最佳答案

我最近也遇到了这个问题。我有一个文件放在资源文件中,我们称之为path我无法阅读它。 @madoke 给出了使用 FileSystem 的解决方案之一。这是另一个,这里我们假设我们在一个容器中,如果不是,我们使用 Java 8 特性。

@Component 
@Log4j2
public class DataInitializer implements 
    ApplicationListener<ApplicationReadyEvent> {

private YourRepo yourRepo; // this is your DataSource Repo

@Value(“${path.to.file}”). // the path to file MUST start with a forward slash: /iaka/myfile.csv
private String path;

public DataInitializer(YourRepo yourRepo) {
    this.yourRepo = yourRepo;
}

@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
    try {
        persistInputData();
        log.info("Completed loading data");
    } catch (IOException e) {
        log.error("Error in reading / parsing CSV", e);
    }
}

private void persistInputData() throws IOException {
    log.info("The path to Customers: "+ path);
    Stream<String> lines;
    InputStream inputStream = DataInitializer.class.getClassLoader().getResourceAsStream(path);
    if (inputStream != null) { // this means you are inside a fat-jar / container
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        lines = bufferedReader.lines();
    } else {
        URL resource = this.getClass().getResource(path);
        String path = resource.getPath();
        lines = Files.lines(Paths.get(path));
    }

    List<SnapCsvInput> inputs = lines.map(s -> s.split(","))
                                     .skip(1) //the column names
                                     .map(SnapCsvInput::new)
                                     .collect(Collectors.toList());
    inputs.forEach(i->log.info(i.toString()));
    yourRepo.saveAll(inputs);

}

}

关于java - 在 Spring boot fat jar 中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41983100/

相关文章:

java - <absolute-ordering> 在 tomcat 7 中不起作用

java - 为什么我必须将每个 Thread.sleep() 调用包装在 try/catch 语句中?

java - 通过尝试从 Google-Cloud-Storage 读取值来授予无效

java - 如何在 spring data JPA 中制作多个保存方法?

java - 独立消费者 (SpringJMS) 在 ActiveMQ 上创建了另一个队列

java - 用于自动 headless Web 客户端的 canoo 或 jwebUnit?

javax.mail.Transport.send0() 不会抛出它所 promise 的异常

java - spring-data-mongodb: findAll() 包含输入文档列表和嵌入式 DBRef 文档的搜索参数

java - Spring Jpa Hibernate 列未转换为查询

javascript - 成功 import-jdl 后,JHipster 实体菜单为空