简体   繁体   中英

Unable to read file from spring boot .jar

I want to access file on my classpath called reports/invoiceSweetChoice.jasper in jar on production server. Whatever I do I get null.

I have tried this.getClass().getResourceAsStream("reports/invoiceSweetChoice.jasper") , tried via InputStream etc. I have printed out content of System.getProperty("java.class.path") and it is empty. Not sure how is that possible. Do you have any suggestion how to resolve this ?

@Autowired private ResourceLoader resLoad;


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

In manifest.mf, the classpath is defined using the class-path key and a space-delimited list of files , as follows:

MANIFEST.MF at root of jarfile.

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

If there are spaces in the jar filename, you should enclose them in quotes.

If it's a webapp, the reports path should be in your BOOT-INF subdirectory of your classpath -- this is automatically performed by maven if you put it in src/main/resources in the standard layout.

EDIT:

Now that you've clarified what you're trying to do, you have 2 approaches. Like I said above, you can grab the file from the BOOT-INF subdirectory of your webapp or you can enumerate the entries in the jar until you find the one you want:

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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM