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

在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

@EnableAutoConfiguration

public 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-proble

m\target>java -jar demo-0.0.1-SNAPSHOT.jar


  .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v1.1.5.RELEASE)

冉冉说
浏览 962回答 3
3回答

吃鸡游戏

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

蛊毒传说

如果您使用的是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);}

慕后森

如果要使用文件: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);}
打开App,查看更多内容
随时随地看视频慕课网APP