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

前端 未结 16 2121
时光说笑
时光说笑 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 10:01

    A File is an abstraction for a file in a filesystem, and the filesystems don't know anything about what are the contents of a JAR.

    Try with an URI, I think there's a jar:// protocol that might be useful for your purpouses.

    0 讨论(0)
  • 2020-11-22 10:02

    This is deliberate. The contents of the "file" may not be available as a file. Remember you are dealing with classes and resources that may be part of a JAR file or other kind of resource. The classloader does not have to provide a file handle to the resource, for example the jar file may not have been expanded into individual files in the file system.

    Anything you can do by getting a java.io.File could be done by copying the stream out into a temporary file and doing the same, if a java.io.File is absolutely necessary.

    0 讨论(0)
  • 2020-11-22 10:02
    private static final String FILE_LOCATION = "com/input/file/somefile.txt";
    
    //Method Body
    
    
    InputStream invalidCharacterInputStream = URLClassLoader.getSystemResourceAsStream(FILE_LOCATION);
    

    Getting this from getSystemResourceAsStream is the best option. By getting the inputstream rather than the file or the URL, works in a JAR file and as stand alone.

    0 讨论(0)
  • 2020-11-22 10:05

    When in a jar file, the resource is located absolutely in the package hierarchy (not file system hierarchy). So if you have class com.example.Sweet loading a resource named "./default.conf" then the resource's name is specified as "/com/example/default.conf".

    But if it's in a jar then it's not a File ...

    0 讨论(0)
提交回复
热议问题