Take the 2-minute tour ×

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)

share|improve this question

1 Answer 1

up vote 5 down vote accepted

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).

share|improve this answer
thanks a lot! so that line returns the same value even if i run it from different classes in the jar right? –  user939345 Sep 11 '11 at 17:30
As long as they are all in the exact same jar, yes they should. –  Femi Sep 11 '11 at 17:38
var path? Mixed metahaphors :) Also explain how to to this in a static method. –  Miserable Variable Sep 11 '11 at 17:57
yep i figured it out, now that i've been able to testing i'm highlighting the green tick! –  user939345 Sep 11 '11 at 23:35
What if I want to get the path of the DIRECTORY in which the jar file is located, rather than the exact .jar path. How can I do this ? Actually I want to write a new file in the same directory as the directory in which jar is present. –  Faizan Mar 7 '13 at 14:05

Your Answer


