为了账号安全,请及时绑定邮箱和手机立即绑定

作为jar运行时找不到类路径资源

作为jar运行时找不到类路径资源

冉冉说 2019-11-07 12:45:53
在Spring Boot 1.1.5和1.1.6中都存在此问题-我正在使用@Value注释加载类路径资源,当我从STS(3.6.0,Windows)中运行应用程序时,它的工作正常。但是,当我运行mvn程序包,然后尝试运行jar时,出现FileNotFound异常。资源message.txt位于src / main / resources中。我已经检查了jar,并确认它在顶层(与application.properties相同)包含文件“ message.txt”。这是应用程序:@Configuration@ComponentScan@EnableAutoConfigurationpublic class Application implements CommandLineRunner {    private static final Logger logger = Logger.getLogger(Application.class);    @Value("${message.file}")    private Resource messageResource;    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }    @Override    public void run(String... arg0) throws Exception {        // both of these work when running as Spring boot app from STS, but        // fail after mvn package, and then running as java -jar        testResource(new ClassPathResource("message.txt"));        testResource(this.messageResource);    }    private void testResource(Resource resource) {        try {            resource.getFile();            logger.debug("Found the resource " + resource.getFilename());        } catch (IOException ex) {            logger.error(ex.toString());        }    }}例外:c:\Users\glyoder\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-problem\target>java -jar demo-0.0.1-SNAPSHOT.jar  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::        (v1.1.5.RELEASE)
查看完整描述

3 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

resource.getFile()期望资源本身在文件系统上可用,即不能嵌套在jar文件中。这就是为什么当您在STS中运行应用程序时它可以工作,但是一旦您构建了应用程序并从可执行jar中运行它后,它就无法工作。建议不要使用getFile()来访问资源的内容getInputStream()。这样一来,无论资源位于何处,您都可以阅读其内容。


查看完整回答
反对 回复 2019-11-07
?
蛊毒传说

TA贡献1895条经验 获得超3个赞

如果您使用的是Spring框架,那么使用Spring框架的读ClassPathResource入String是非常简单的FileCopyUtils:


String data = "";

ClassPathResource cpr = new ClassPathResource("static/file.txt");

try {

    byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());

    data = new String(bdata, StandardCharsets.UTF_8);

} catch (IOException e) {

    LOG.warn("IOException", e);

}


查看完整回答
反对 回复 2019-11-07
?
慕后森

TA贡献1802条经验 获得超5个赞

如果要使用文件:


ClassPathResource classPathResource = new ClassPathResource("static/something.txt");


InputStream inputStream = classPathResource.getInputStream();

File somethingFile = File.createTempFile("test", ".txt");

try {

    FileUtils.copyInputStreamToFile(inputStream, somethingFile);

} finally {

    IOUtils.closeQuietly(inputStream);

}


查看完整回答
反对 回复 2019-11-07
  • 3 回答
  • 0 关注
  • 948 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信