Netbeans 内置 .jar 不适用于内部的类文件
问题已经解决(检查答案)。
今天我注意到另一个问题:当项目完成时, 我必须执行生成的 .jar 才能启动程序,但它不起作用,因为在 Netbeans 外部访问/打开 jar 时出现错误:NullPointer (where to load a file)。
是否可以使用 Java/Netbeans 中的类文件打开一个文件,该文件在 Netbeans 中甚至在任何目录中都可以工作?
我已经在网站上找到了一些关于我的问题的线程,但没有一个有帮助。
代码:
File file = new File(URLDecoder.decode(this.getClass().getResource("file.xml").getFile(), "UTF-8"));
I had problems while finding the path of file(s) in Netbeans..
Problem is already solved (checked answer).
Today I noticed another problem: When project is finished,
I have to execute the generated .jar to launch the program, but it doesn't work because an error occurs: NullPointer (where to load a file) when accessing/openning jar outside Netbeans.
Is it possible to open a file with the class file in Java/Netbeans which works in Netbeans and even in any directory?
I've found already some threads about my problem in site but none was helpful.
Code:
File file = new File(URLDecoder.decode(this.getClass().getResource("file.xml").getFile(), "UTF-8"));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您遇到的问题是 File 仅引用文件系统上的文件,而不引用 jar 中的文件。
如果您想要更通用的定位器,请使用 getResource 提供的 URL。但是,通常您不需要知道文件的位置,您只需要它的内容,在这种情况下您可以使用 getResourceAsInputStream()
这一切都假设您的类路径配置正确。
The problem you have is that File only refer to files on the filesystem, not files in jars.
If you want a more generic locator, use a URL which is what getResource provides. However, usually you don't need to know the location of the file, you just need its contents, in which case you can use getResourceAsInputStream()
This all assumes your class path is configured correctly.
是的,您应该能够在 java 进程可以访问的文件系统上的任何位置加载文件。您只需要在 getResource 调用中显式设置路径即可。
例如:
Yes, you should be able to load a file anywhere on your file system that the java process has access to. You just need to have the path explicitly set in your getResource call.
For example: