How to reference a resource file correctly for JAR and Debugging?

前端 未结 7 438
不思量自难忘°
不思量自难忘° 2020-12-02 21:58

I have a nasty problem referencing resources when using a Maven project and Jar files...

I have all my resources in a dedicated folder /src/main/resources which is p

相关标签:
7条回答
  • 2020-12-02 22:58

    Maybe this method can help for some situations.

    public static File getResourceFile(String relativePath)
    {
        File file = null;
        URL location = <Class>.class.getProtectionDomain().getCodeSource().getLocation();
        String codeLocation = location.toString();
        try{
            if (codeLocation.endsWith(".jar"){
                //Call from jar
                Path path = Paths.get(location.toURI()).resolve("../classes/" + relativePath).normalize();
                file = path.toFile();
            }else{
                //Call from IDE
                file = new File(<Class>.class.getClassLoader().getResource(relativePath).getPath());
            }
        }catch(URISyntaxException ex){
            ex.printStackTrace();
        }
        return file;
    }
    
    0 讨论(0)
提交回复
热议问题