无法从spring boot.jar读取文件

7vhp5slm  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(394)

我想访问名为 reports/invoiceSweetChoice.jasper 在生产服务器的jar中。不管我做什么,我都得到空值。
我试过了 this.getClass().getResourceAsStream("reports/invoiceSweetChoice.jasper") ,通过 InputStream 我已经打印出了 System.getProperty("java.class.path") 它是空的。不知道怎么可能。你对如何解决这个问题有什么建议吗?

hmmo2u0o

hmmo2u0o1#

@Autowired private ResourceLoader resLoad;

void someMethod() {
    Resource r = resLoad.getResource("classpath:reports/file.abc");
    r.getInputStream()...
    ...
w80xi6nr

w80xi6nr2#

在manifest.mf中,使用类路径键和以空格分隔的文件列表定义类路径,如下所示:
文件根目录下的manifest.mf。

Class-Path: hd1.jar path/to/label007.jar path/to/foo.jar

如果jar文件名中有空格,应该用引号括起来。
如果它是一个webapp,那么reports路径应该在类路径的boot-inf子目录中——如果将它放在标准布局的src/main/resources中,这将由maven自动执行。
编辑:
既然你已经澄清了你要做的事情,你有两种方法。就像我上面说的,你可以从你的webapp的boot inf子目录中获取文件,或者你可以枚举jar中的条目,直到找到你想要的:

JarInputStream is = new JarInputStream(new FileInputStream("your/jar/file.jar"));
JarEntry obj = null
while ((obj = is.getNextJarEntry()) != null) {
   JarEntry entry = (JarEntry)obj;
   if (entry.getName().equals("file.abc")) {
        ByteArrayOutputStream baos = new ByetArrayOutputStream(); 
        IOUtils.copy(jarFile.getInputStream(entry), baos);
        String contents = new String(baos.toByteArray(), "utf-8");
        // your entry is now read into contents
   }
}

相关问题