Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a file from a JAR in the same folder

I need to acces (create and read) a file from a JAR file (executable jar), and that file should be created in the same directory as the JAR

I tried this.getClass().getResource("myFile") but since the jar has packages in it, it won't work..

I also tried write just File f = new File("myFile"); f.createNewFile();

and that works if i execute the JAR from the terminal, but if i execute the JAR by double-clicking it, the file is created in my home directory -.-''

how do i access a file being SURE that that file is in the SAME directory as the JAR file?

(of course also getting the jar absolute path would do the trick since i can get the parent folder from it)

like image 764
Pronte Avatar asked Sep 11 '11 17:09

Pronte


1 Answers

This will give you the full path to the Jar:

String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

EDIT: sorry, was in javascript mode when I wrote that :). As was so politely requested, in a static method you should be able to do this:

String path = Me.class.getProtectionDomain().getCodeSource().getLocation().getPath();

(where the class name is Me).

like image 119
Femi Avatar answered Sep 27 '22 00:09

Femi