Netbeans 内置 .jar 不适用于内部的类文件

发布于 2024-10-08 11:47:17 字数 531 浏览 0 评论 0原文

我在 Netbeans 中查找文件路径时遇到问题.

问题已经解决(检查答案)。

今天我注意到另一个问题:当项目完成时, 我必须执行生成的 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沫尐诺 2024-10-15 11:47:17

您遇到的问题是 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.

迷路的信 2024-10-15 11:47:17

是的,您应该能够在 java 进程可以访问的文件系统上的任何位置加载文件。您只需要在 getResource 调用中显式设置路径即可。

例如:

File file = new File(URLDecoder.decode(this.getClass().getResource("C:\\foo\\bar\\file.xml").getFile(), "UTF-8"));

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:

File file = new File(URLDecoder.decode(this.getClass().getResource("C:\\foo\\bar\\file.xml").getFile(), "UTF-8"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文