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

前端 未结 7 478
不思量自难忘°
不思量自难忘° 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:46

    Once you pack the JAR, your resource files are not files any more, but stream, so getResource will not work!

    Use getResourceAsStream.

    To get the "file" content, use https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html:

    static public String getFile(String fileName)
    {
            //Get file from resources folder
            ClassLoader classLoader = (new A_CLASS()).getClass().getClassLoader();
    
            InputStream stream = classLoader.getResourceAsStream(fileName);
    
            try
            {
                if (stream == null)
                {
                    throw new Exception("Cannot find file " + fileName);
                }
    
                return IOUtils.toString(stream);
            }
            catch (Exception e) {
                e.printStackTrace();
    
                System.exit(1);
            }
    
            return null;
    }
    

提交回复
热议问题