问题
I'm trying to read from a file that is packaged up inside a JAR, along with the class that reads it. To do this, I use the following:
getClass().getClassLoader().getResourceAsStream(file)
This works fine when I create and run the JAR file on OSX, but if I create and run the JAR file on windows, the above line returns null.
Am I missing something here? If I create the JAR on OSX and run it on Windows it works fine. The problem only occurs when I create the JAR on windows.
EDIT: It's worth mentioning that there is no folder hierarchy within the JAR file. Everything is stored at one level, thus the class reading the file and the file itself are both in the same directory. Additionally, this is how I'm creating the JAR file, on both OSX and Windows:
jar -cmf manifest.mf run.jar *.class file1 file2
EDIT 2: The file I am trying to load is a java .properties file. I take it that's not what is causing the issue?
回答1:
Skip the classloader part. Just getClass().getResource....
回答2:
Try it this way getClass().getResourceAsStream("/file1").
回答3:
When using file separators, don't hard code them! Use java.io.File.separator instead: http://docs.oracle.com/javase/7/docs/api/java/io/File.html#separator
来源:https://stackoverflow.com/questions/15961233/reading-file-from-within-jar-not-working-on-windows