简体   繁体   中英

How import a file in a jar?

I have this project that it has this structure

Home
 graphics
    field.txt
    example.java

I need to load field.txt in my example.java in jar and I use:

getClass().getClassLoader().getResource("field.txt").toUri();

but this code it give me "Null Pointer exception" .Anyone can help me?

要读取它必须在类路径中的文件,可以将该文件放入包含.class文件的文件夹中,或者使用java -cp选项将其添加到类路径中。

example.class.getResource(“/graphics/field.txt“);

The class should belong to the same jar. For Class.getResource a relative “field.txt“ is possible (same package). With ClassLoader an absolute path for all classpaths is sought: “graphics/field.txt“.

To immediately read (never write) use getResourceAsStream or the URI of the getResource . One can use a Path on the URI. Files.copy(...) .


One cannot at least should not) write a resource file (as it can reside in a jar jar:file://... ; and jar might even be sealed; and resources might be cached by the jvm). Keep it as read-only template. Never File .

One technique is to create an application named directory in System.getProperty("user.home") and copy the template there.

The issue is not so much your code, but how you build and package your jar file. You will have to clarify how you are currently building your jar (using ant, maven, eclipse, etc ?).

Many articles will also advise you to separate out your resources from your source code (.java), and many IDE will support this separation direclty by allowing you to mark a folder as a resource folder. Even maven will allow you to customize this.

See following articles:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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