jar-File的InputStream返回null [英] InputStream from jar-File returns always null
问题描述
我知道这个问题已被多次询问,但我认为我的问题与其他问题略有不同:
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);
文件对象newFile完全正常(找到.jar文件,你可以得到它元数据,如newFile.length()等)
The File-Object newFile is completely fine (the .jar file has been found and you can get its meta-data like newFile.length() etc)
另一方面,InputStream总是返回null。
我知道javadoc说如果找不到具有此名称的资源, getResourceAsStream()
为null,但文件就在那里! (显然,因为它在文件对象中)
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)
任何人都知道为什么会发生这种情况以及如何修复它以便我可以在InputStream中获取.jar文件?
Anyone know why this happens and how i can fix it so that i can get the .jar File in the InputStream?
推荐答案
getResourceAsStream()
方法不会从中加载文件文件系统;它从类路径加载资源。您可以使用它来加载例如打包在JAR中的属性文件。您无法使用它从文件系统加载文件。
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.
因此,如果您的文件驻留在文件系统上,而不是在JAR文件中,请更好地使用< a href =http://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html\"rel =nofollow> FileInputStream
等级。
So, if your file resides on the file system, rather than in your JAR file, better use the FileInputStream
class.
这篇关于jar-File的InputStream返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!