无法从 spring 引导 .jar 读取文件
Unable to read file from spring boot .jar
我想在生产服务器上的 jar 中访问类路径中名为 reports/invoiceSweetChoice.jasper
的文件。无论我做什么,我都会得到 null。
我试过this.getClass().getResourceAsStream("reports/invoiceSweetChoice.jasper")
,通过InputStream
等试过。我已经打印出System.getProperty("java.class.path")
的内容,但它是空的。不知道这怎么可能。您对如何解决这个问题有什么建议吗?
@Autowired private ResourceLoader resLoad;
void someMethod() {
Resource r = resLoad.getResource("classpath:reports/file.abc");
r.getInputStream()...
...
在manifest.mf中使用class-path key and a space-delimited list of files定义classpath,如下:
MANIFEST.MF 在 jarfile 的根目录。
Class-Path: hd1.jar path/to/label007.jar path/to/foo.jar
如果 jar 文件名中有空格,您应该将它们括在引号中。
如果它是一个网络应用程序,报告路径应该在您的类路径的 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
}
}
我想在生产服务器上的 jar 中访问类路径中名为 reports/invoiceSweetChoice.jasper
的文件。无论我做什么,我都会得到 null。
我试过this.getClass().getResourceAsStream("reports/invoiceSweetChoice.jasper")
,通过InputStream
等试过。我已经打印出System.getProperty("java.class.path")
的内容,但它是空的。不知道这怎么可能。您对如何解决这个问题有什么建议吗?
@Autowired private ResourceLoader resLoad;
void someMethod() {
Resource r = resLoad.getResource("classpath:reports/file.abc");
r.getInputStream()...
...
在manifest.mf中使用class-path key and a space-delimited list of files定义classpath,如下:
MANIFEST.MF 在 jarfile 的根目录。
Class-Path: hd1.jar path/to/label007.jar path/to/foo.jar
如果 jar 文件名中有空格,您应该将它们括在引号中。
如果它是一个网络应用程序,报告路径应该在您的类路径的 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
}
}