简体   繁体   中英

Include external file (not jar) to executable jar

If I load some (say *.txt) file to my java app, how can I inlcude it to my final executable jar to make it portable (means if I move my jar to another machine it's not required to move this *.txt file with it)?

Note that I don't need the content of file I need the file itself . And how should I write the path to this file from the code?

String path = "path/to/file/"; //Yeah it should be String

I'm using IntellijIDEA and I can include any files to my final jar but can't figure out where to place it. Thanks.

Just put your file into project's src folder - for example src/resource/file.txt . When you build your project, whole src content will be put in resulting jar. You can access your file with the following code:

this.getClass().getResource("/resource/file.txt");    

An example of reading all lines:

URL url = this.getClass().getResource("/resource/file.txt");
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);    

You need something like the below

<target name="somejar" depends="compile">
      <jar jarfile="${somejar.jar}">
        <fileset dir="${bin.dir}">
          <include name="**/*.class"/>
        </fileset>
        <zipgroupfileset dir="lib" includes="*.jar"/>
        <fileset dir="${basedir}">
          <include name="config/*.properties"/>
          <include name="config/*.txt"/>
        </fileset>
      </jar>
    </target>

this will put all the needed class and property files together. You can code the location of file from the base of the project till you reach the file.

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