简体   繁体   English

访问打包到jar文件中的文件

[英]Accessing files packaged into a jar file

I created a jar file with a runnable compiled class and some template files (text). 我创建了一个带有可运行编译类和一些模板文件(文本)的jar文件。 I now want to use the text files packaged into the jar for distribution in the application as File objects. 我现在想要使用打包到jar中的文本文件在应用程序中作为File对象进行分发。

I tried to just use relative paths which did not work. 我试图使用不起作用的相对路径。 How do I get a File object pointing to a text file which is in the jar? 如何获取指向jar中文本文件的File对象?

Is there a way to do this so it will work both when running the unpackaged class files and from a jar with the same code, or will I need to use separate functions? 有没有办法做到这一点所以它既可以在运行未打包的类文件时运行,也可以从具有相同代码的jar运行,或者我是否需要使用单独的函数?

from inside jar you can use it like Class.getResourceAsStream(String) , or something similar. 从jar里面你可以像Class.getResourceAsStream(String)或类似的东西一样使用它。

from out side its not the file its jar so you will have to extract it in order to actually use inside file 从外面它不是文件的jar,所以你必须提取它,以实际使用内部文件

If you are using the JAR within your application, then Class.getResourceAsStream(String) will do. 如果您在应用程序中使用JAR,那么Class.getResourceAsStream(String)将执行。

Alternatively, if you're using Servlet, then ServletContext.getResourceAsStream(String) will also do. 或者,如果您使用的是Servlet,那么ServletContext.getResourceAsStream(String)也可以。

These 2 methods returns an InputStream (of your resource data) and not your File object as you rightfully want. 这两个方法返回一个InputStream (属性数据),而不是你想要的File对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM