简体   繁体   中英

Built java project in Netbeans doesn’t include external TEXT files

Sorry if the question is basic. I'm trying to build a java project that include text files :

    File file = new File("data/include/foo.txt");

Problem is that with Netbeans, Built and Clean actions are done without taking into account external text files. Can you please help me solving this problem.

In Netbeans there are basically two types of java projects. One is using ANT as its build machine and one is using maven .

Using ANT to build:

You have to modify or build a build.xml . Netbeans offers some targets in its standard build.xml to trigger events on each part of the build process.

So to include some additional resource files (in your case some text files) you should add your build.xml with a target like

<target name="-post-jar">
    <jar destfile="dist/myjar.jar" update="true">
        <fileset dir="${basedir}">
            <include name="data/include/*"/>
        </fileset>
    </jar>
</target>

It means that after your JAR is build the files from ${basedir}/files/* are included as well.

Using MAVEN to build:

Netbeans uses here completely Mavens infrastructure. So Maven does have a standard mechanism to recognize resource files to include. It all comes down to place these files in a specific place of the project. Assuming you did not change this standard directory layout of maven JAR projects is is something like:

Project
   src
       main
           java
           resources
   ...

So all files placed in src/main/resources (including subfolders) are included in your JAR automatically.

Read more here

Edit 1:

To access this resource files you cannot use File objects. This is done using the class own getResource methods:

App.class.getResourceAsStream("data.xml")

App.class.getResource("data.xml")

Here my class is App and my datafile is data.xml which is in the same directory as my class. This is relative adressed. But if you use a path with a heading / then your path is JAR file absolute. Read more about this here .

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