引用 jar 中的数据文件
我的Java程序引用了很多数据文件。我将它们与 src/ 和 bin/ 一起放在名为 data/ 的顶级目录中。在 Eclipse 中,对 data/ 和 ../data/ 的引用似乎都有效。当我从命令行运行它时,只有 ../data/ 有效。
当我将 bin/ 和 data/ 目录放入 jar 中并正确设置入口点时,它似乎不知道我希望它访问 jar 内的 data/ 目录。我能够让它工作的唯一方法是设置对 ../data/ 的引用并将 jar 放在 bin 目录中。这显然对我没有任何好处,因为它不是独立的。
我需要对参考文献做什么才能使其发挥作用?
谢谢
My Java program references a lot of data files. I put them in a top level directory called data/, along with src/ and bin/. In Eclipse, references to data/ and ../data/ both seem to work. When I run it from the command line, only ../data/ works.
When I put the bin/ and data/ directories in a jar and correctly set the entry point, it doesn't seem to know that I want it to access the data/ directory inside the jar. The only way I've been able to get it to work is by setting the references to ../data/ and placing the jar in the bin directory. This obviously doesn't do me any good, because it's not self-contained.
What do I need to do to the references to make them work?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您以类路径相关的方式访问这些文件,无论是在 Eclipse 中还是在已编译的 JAR 中。
您可以采用多种方法来实现此目的,但仅适用于 JDK 的基本方法是使用 Class 的 getResourceAsStream() 方法,使您可以访问可以读入的 InputStream 对象。
I'd recommend you access the files in a classpath-relative way, whether in Eclipse or in a compiled JAR.
There are a few ways you might go about it, but a basic JDK-only approach would be to use Class's
getResourceAsStream()
method, giving you access to an InputStream object that you can read in.如果您的资源位于 jar 文件中,请考虑使用此方法来读取它们:
这将查找相对于类(可能位于 jar 中)的资源,而不是相对于工作目录的资源。
If your resources are in a jar file, consider using this method to read them:
This looks for the resource relative to a class (which may be in a jar), rather than relative to the working directory.
谢谢你们给我指明了这条路,伙计们。我最终做了一个非常糟糕的解决方法,因为我还不太擅长 IO。我使用 getClass() 构造一个 URL:
http://forums.sun.com/thread .jspa?threadID=5258488
然后从此字符串创建一个新的 File 对象 (new File(file)):
String file = url.toString().replaceFirst("file:", "");
这使我能够保留引用文件对象的相同代码。
Thanks for pointing me down this path, guys. I ended up doing a really hacked up workaround because I'm not very good with IO yet. I used getClass() to construct a URL:
http://forums.sun.com/thread.jspa?threadID=5258488
Then made a new File object from this string (new File(file)):
String file = url.toString().replaceFirst("file:", "");
This allowed me to keep the same code that referenced the file objects.