0

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.

Daria
  • 861
  • 11
  • 29
  • 1
    possible duplicate of [adding resources in intellij for java project](http://stackoverflow.com/questions/18717038/adding-resources-in-intellij-for-java-project) – Joe Jan 05 '15 at 11:14
  • @Joe Thanks, looks usefull, but so much letters :D, I'll check it out – Daria Jan 05 '15 at 11:38
  • @Joe But as you see that question hasn't accepted answer and the author marked that it doesn't solve his question – Daria Jan 05 '15 at 11:47
  • possible duplicate of [Accessing JAR resources](http://stackoverflow.com/questions/2639943/accessing-jar-resources) – Raedwald Jan 06 '15 at 21:31

2 Answers2

3

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);    
matoni
  • 2,479
  • 21
  • 39
  • Thanks for input. But my function waits for a `string` format file path as a parameter. Using `toString()` I get the string like `file:/full/path/to/file/` so it's not usable for me. – Daria Jan 06 '15 at 08:10
  • Thank you very much! you save my day – mee Jan 29 '20 at 11:11
0

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.

Kalaiarasan Manimaran
  • 1,598
  • 1
  • 12
  • 18