Java .class.getResourceAsStream()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14977851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:03:57  来源:igfitidea点击:

Java .class.getResourceAsStream()

javajarinputstream

提问by

To the best of my knowledge, Class.getResourceAsStream()gets an InputStreamdirected at a file within the .jar file? If I'm wrong about this, please correct me.

据我所知,Class.getResourceAsStream()获取InputStream.jar 文件中的一个文件?如果我错了,请纠正我。

Is there any way to temporarily 'load' an external file into the .jar, so that the getResourceAsStream()method can retrieve it?

有什么方法可以将外部文件临时“加载”到 .jar 中,以便该getResourceAsStream()方法可以检索它?

For example loading C:/folder/file.txtinto the .jar so that MyClass.class .getResourceAsStream("file.txt")would return a working InputStreamto the file, or at least a copy of it that has been 'loaded' temporarily into the .jar.

例如加载C:/folder/file.txt到 .jar 中,以便MyClass.class .getResourceAsStream("file.txt")将工作返回InputStream到文件,或者至少是它的一个副本,它已经临时“加载”到 .jar 中。

I'm sorry I've worded this so badly, I hope you can understand what I'm trying to do, wasn't quite sure how to explain it simply.

很抱歉我的措辞如此糟糕,我希望你能理解我想要做什么,不太确定如何简单地解释它。

采纳答案by John Smith

Nope, the getResourceAsStream() method gets a file from the classpath. That includes anything that is specified like this on the command line (windows version, linux uses ':' as delimiter):

不, getResourceAsStream() 方法从类路径中获取文件。这包括在命令行上指定的任何内容(windows 版本,linux 使用 ':' 作为分隔符):

java -cp "path;path2;path3;path4/some.jar" your.main.Clazz

回答by SudoRahul

this.getClass().getResourceAsStream("myImage.png");

Make sure your image is there in the classpath. Need not put it into any JARas such.

确保您的图像在类路径中。不需要把它放在任何JAR这样的地方。