gpt4 book ai didi

java - JAR 中的 Spring Boot ClassPathResource

转载 作者:行者123 更新时间:2023-11-30 02:35:58 26 4
gpt4 key购买 nike

在我的 Spring Boot 1.5 应用程序中,我使用 ClassPathResource 读取应用程序 JAR 的静态文件:

// ...
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

@Slf4j
@Service
public class MyService {
private Resource resource = new ClassPathResource("a.txt");
private List<String> myStrings;
public MyService() {
myStrings = load(resource);
}

private List<String> load(Resource resource) {
try(Stream<String> stream = Files.lines(Paths.get(resource.getURI()))) {
myStrings = stream.filter(/* my filter */)
.collect(Collectors.toList());
} catch (IOException x) {
log.error("Failed to read '{}'.", resource.getFilename());
}
}
}

但是失败了:

Caused by: java.nio.file.FileSystemNotFoundException: null
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171) ~[zipfs.jar:1.8.0_121]
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157) ~[zipfs.jar:1.8.0_121]
at java.nio.file.Paths.get(Paths.java:143) ~[na:1.8.0_121]
at MyService.load(MyService.java:53) ~[classes!/:2.0.0-SNAPSHOT]
//...

如何读取嵌入在我的应用程序 JAR 中的 ClassPathResource

最佳答案

JDK 的 Paths.get 无法解析 JAR 文件中的资源,因此替换:

    Files.lines(Paths.get(resource.getURI()))

与:

    new BufferedReader(new InputStreamReader(resource.getInputStream())).lines();

关于java - JAR 中的 Spring Boot ClassPathResource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43060265/

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