Java JAR中的Spring引导类路径资源
在我的Spring Boot 1.5应用程序中,我使用Java JAR中的Spring引导类路径资源,java,spring,spring-boot,Java,Spring,Spring Boot,在我的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 Class
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());
}
}
}
如何读取嵌入在我的应用程序JAR中的
ClassPathResource
?JDK的路径。get
无法解析JAR文件中的资源,因此请替换:
Files.lines(Paths.get(resource.getURI()))
与:
Files.lines(Paths.get(resource.getURI()))
new BufferedReader(new InputStreamReader(resource.getInputStream())).lines();