InputStream from jar-File returns always null

怎甘沉沦 提交于 2019-12-11 19:17:05

问题


i know this question has been asked several times, but i think my problem differs a bit from the others:

String resourcePath = "/Path/To/Resource.jar";

File newFile = new File(resourcePath);
InputStream in1 = this.getClass().getResourceAsStream(resourcePath);
InputStream in2 = this.getClass().getClassLoader().getResourceAsStream(resourcePath);

The File-Object newFile is completely fine (the .jar file has been found and you can get its meta-data like newFile.length() etc)

On the other hand the InputStream always return null. I know the javadoc says that the getResourceAsStream() is null if there is no resource found with this name, but the File is there! (obviously, because it's in the File-Object)

Anyone know why this happens and how i can fix it so that i can get the .jar File in the InputStream?


回答1:


The getResourceAsStream() method doesn't load a file from the file system; it loads a resource from the classpath. You can use it to load, for example, a property file that's packaged inside your JAR. You cannot use it to load a file from the file system.

So, if your file resides on the file system, rather than in your JAR file, better use the FileInputStream class.



来源:https://stackoverflow.com/questions/15830532/inputstream-from-jar-file-returns-always-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!