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

前端 未结 7 482
不思量自难忘°
不思量自难忘° 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.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.getClassLoader().getResource(relativePath).getPath());
            }
        }catch(URISyntaxException ex){
            ex.printStackTrace();
        }
        return file;
    }
    

提交回复
热议问题