java 读取 jar 包内的 xml 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2552793/
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
reading xml file inside a jar-package
提问by B. T.
Here's my structure:
这是我的结构:
- com/mycompany/ValueReader.class
- com/mycompany/resources/values.xml
- com/mycompany/ValueReader.class
- com/mycompany/resources/values.xml
I can read the file in my Eclipse project, but when I export it to a .jar it can never find the values.xml.
我可以在我的 Eclipse 项目中读取该文件,但是当我将它导出到 .jar 时,它永远找不到 values.xml。
I tried using ValueReader.class.getResource() and ValueReader.class.getResourceAsStream() but it doesn't work.
我尝试使用 ValueReader.class.getResource() 和 ValueReader.class.getResourceAsStream() 但它不起作用。
What's the problem here? How do I get a File-object to my values.xml?
这里有什么问题?如何将文件对象获取到我的 values.xml?
B.
B.
回答by Brian Agnew
You can't get a Fileobject (since it's no longer a file once it's in the .jar), but you should be able to get it as a stream via getResourceAsStream(path);, where pathis the completepath to your class.
你不能得到一个File对象(因为一旦它在 .jar 中就不再是一个文件),但你应该能够通过 将它作为流获取,你的类的完整路径getResourceAsStream(path);在哪里。path
e.g.
例如
/com/mycompany/resources/values.xml
回答by tbodt
You can't get a Filefor the file because it's in a jar file. But you can get an input stream:
您无法获得File该文件的a ,因为它位于 jar 文件中。但是你可以得到一个输入流:
InputStream in = ValueReader.class.getResourceAsStream("resources/values.xml");
getResourceAsStreamand getResourceconvert the package of the class to a file path, then add on the argument. This will give a stream for the file at path /com/mycompany/resources/values.xml.
getResourceAsStream和getResource转换的类文件路径的包,然后添加上的说法。这将为 path 处的文件提供一个流/com/mycompany/resources/values.xml。
回答by Premkumar Karnan
This will work...
这将工作...
Thread.currentThread().getContextClassLoader().getResource("com/mycompany/resources/values.xml")
回答by WALID
You can extract the jar then take what you want, in the same class-path using :
您可以提取罐子,然后在相同的类路径中使用您想要的东西:
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new
FileInputStream(zipfile.getCanonicalFile())));

