score:0 is a java source file which is not available after compilation to bytecode. the source directory it was in is not available, too.

dir2 is the file of the directory you execute the .class file in. it seams that this happens to be d:\workspace\project1 but you can't rely on this.


your dir2 points to working directory (new file(".")). you can't get the location of your sources this way. your file could sit inside the package (e.g. you should just manually concat the "src" to current working directory and then replace file package dots (.) with file.pathseparator. in that way you will build the full path to your file.


string fullfilepath = "h:\\shared\\testing\\abcd.bmp";
    file file = new file(fullfilepath);

    string filepath = file.getabsolutepath().substring(0,fullfilepath.lastindexof(file.separator));

output: h:\shared\testing


if you are doing this to try to read a file from the classpath, then check out this answer: how to really read text file from classpath in java

essentially you can do this

inputstream in = this.getclass().getclassloader()

otherwise, if you have some other requirement, one option is to pass through the src directory as a jvm arg when the application begins and then just read it back.


/** the actual file running */
public static final file    jar_file = new file(myclass.class.getprotectiondomain().getcodesource().getlocation().getpath();

/** the path to the main folder where the file .jar is run */
public static final string  base_directory  = (jar_file != null ? jar_file.getabsolutepath().replace(jar_file.getname(), "") : "notfound");

this will work for you both in normal java execution and jar execution. this is the solution i am using in my project.

Related Query

More Query from same tag