How to get a path to a resource in a Java JAR file

前端 未结 16 2455
时光说笑
时光说笑 2020-11-22 09:23

I am trying to get a path to a Resource but I have had no luck.

This works (both in IDE and with the JAR) but this way I can\'t get a path to a file, only the file

16条回答
  •  面向向阳花
    2020-11-22 09:47

    Maybe this method can be used for quick solution.

    public class TestUtility
    { 
        public static File getInternalResource(String relativePath)
        {
            File resourceFile = null;
            URL location = TestUtility.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();
                    resourceFile = path.toFile();
                }else{
                    //Call from IDE
                    resourceFile = new File(TestUtility.class.getClassLoader().getResource(relativePath).getPath());
                }
            }catch(URISyntaxException ex){
                ex.printStackTrace();
            }
            return resourceFile;
        }
    }
    

提交回复
热议问题