Classpath resource not found when running as jar

来源:互联网 发布:iframe 端口不同 跨域 编辑:程序博客网 时间:2024/06/02 00:01
File file = new ClassPathResource("countries.xml").getFile();File file= ResourceUtils.getFile("classpath:test.txt");
Resource resource = new ClassPathResource(templateFile);String file = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));

/**
* {@link Resource} implementation for class path resources. Uses either a
* given {@link ClassLoader} or a given {@link Class} for loading resources.
*
* Supports resolution as {@code java.io.File} if the class path
* resource resides in the file system, but not for resources in a JAR.
* Always supports resolution as URL.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 28.12.2003
* @see ClassLoader#getResourceAsStream(String)
* @see Class#getResourceAsStream(String)
*/
public class ClassPathResource extends AbstractFileResolvingResource {


resource.getFile() expects the resource itself to be available on the file system, i.e. it can’t be nested inside a jar file. This is why it works when you run your application in STS but doesn’t work once you’ve built your application and run it from the executable jar. Rather than using getFile() to access the resource’s contents, I’d recommend using getInputStream() instead. That’ll allow you to read the resource’s content regardless of where it’s located.

https://stackoverflow.com/questions/25869428/classpath-resource-not-found-when-running-as-jar
https://stackoverflow.com/questions/36371748/spring-boot-access-static-resources-missing-scr-main-resources

阅读全文
0 0