How to get a file in the same dir with the jar-executable

Hi,
I need to read/write a file that exists in the same directory with the jar-executable. How can i do that? I think that when i specify no path for the file, the file has to be in current path. (Is that right?)
Note: I do not know in which directory the jar and the file are.
Thanx in advance

Hi,
I need to read/write a file that exists in the same
directory with the jar-executable. How can i do that?
I think that when i specify no path for the file, the
file has to be in current path. (Is that right?)
Note: I do not know in which directory the jar and
the file are.
Thanx in advance
When you specify no path for the file, the file has to be in the directory where the virtual machine was started. ( the directory the java command was invoked in .)
If you can't control the directory in which the vm is started, but you know the name of the .jar file you can do the following. This trick takes advantage of the fact that if you are using classes in a jar file, the name of the jar file must be in your classpath.
public static String getPathOfJar( String nameOfJar )
throws Exception
StringTokenizer st = new StringTokenizer(
System.getProperty( "java.class.path" ) ,
          System.getProperty( "path.separator" ) );
String jarfile = "";
while ( st.hasMoreTokens() )     
String token = st.nextToken();
if ( token.indexOf( nameOfJar ) > -1 )
jarfile = token;
break;
if ( jarfile.equals("") ) throw new Exception( "Jar not found in classpath" );
String path = jarfile.substring( 0 , jarfile.indexOf( nameOfJar ) );
return path;
//To open a file in the same directory as the sun archive tools.jar
File f = new File( getPathofJar( "tools.jar" ) + "someFile.txt" );

Similar Messages

Maybe you are looking for