我们有一个 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/