简体   繁体   中英

Get absolute path of resource file inside a jar

I want to access a file inside a resource folder of the current jar running. The file is inside of My_app.jar where is located to /apps/dashboard/ I tried to access it like this

String customScriptPath = "script/template.sh";
public String getTemplatePath() {
        Resource temp=  new ClassPathResource(this.customScriptPath, this.getClass().getClassLoader()); 
        try {
            File templateFile =  temp.getFile();
            logger.info("Script template path = "+templateFile.getAbsolutePath());
            return templateFile.getAbsolutePath();
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

and I got this error

class path resource [script/template.sh] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/apps/dashboard/My_app.jar!/BOOT-INF/classes!/script/template.sh

You can't use File to access the template.sh . File is used to reference files in the file system. In your case, you are trying to reference something inside a jar file.

If you want to read content of template.sh , take a stream using Resource.getInputStream() . If you want to log location of the file, use Resource.getURL() .

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