简体   繁体   English

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

[英]Netbeans Built .jar doesn't work with class file inside

I had problems while finding the path of file(s) in Netbeans. 在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. 今天我注意到另一个问题:当项目完成时,我必须执行生成的.jar来启动程序,但它不起作用,因为发生错误:NullPointer(在哪里加载文件)访问/打开Netbeans外面的jar 。

Is it possible to open a file with the class file in Java/Netbeans which works in Netbeans and even in any directory? 是否可以使用Java / Netbeans中的类文件打开一个文件,该文件在Netbeans甚至任何目录中都可以使用?

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"));

The problem you have is that File only refer to files on the filesystem, not files in jars. 您遇到的问题是,文件仅引用文件系统上的文件,而不引用jar中的文件。

If you want a more generic locator, use a URL which is what getResource provides. 如果您想要更通用的定位器,请使用getResource提供的URL。 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() 但是,通常不需要知道文件的位置,只需要文件的内容即可,在这种情况下,可以使用getResourceAsInputStream()

This all assumes your class path is configured correctly. 所有这些都假定您的类路径配置正确。

Yes, you should be able to load a file anywhere on your file system that the java process has access to. 是的,您应该能够在文件系统的任何位置加载java进程可以访问的文件。 You just need to have the path explicitly set in your getResource call. 您只需要在getResource调用中明确设置路径。

For example: 例如:

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

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

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