亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

作為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 關注
  • 1079 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號