解决springboot读取jar包中文件的问题

异常

java.nio.file.NoSuchFileException: file:/app.jar!/BOOT-INF/classes!/static/xxx.pdf
    at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
    at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
    at java.nio.file.Files.newByteChannel(Files.java:361)
    at java.nio.file.Files.newByteChannel(Files.java:407)
    at java.nio.file.Files.readAllBytes(Files.java:3152)

解决方案

InputStream stream = getClass().getClassLoader().getResourceAsStream("static/xxx.pdf");
File targetFile = new File("xxx.pdf");
FileUtils.copyInputStreamToFile(stream, targetFile);

doc

  • Classpath resource not found when running as jar

  • How to get files from resources folder. Spring Framework

你可能感兴趣的:(springboot)