• Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding the main class path  RSS feed

 
Philippe Maquet
Bartender
Posts: 1872
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everybody,
Preparing my SCD assignment, I tried to find out a way to know the start directory of my application (I mean the directory my main class is in).
Surprise ! It seems (confirmed by other threads on this forum) that there is no simple method to get that basic information in Java (something as simple as the well-known Delphi "ExtractFilePath(Application.exeName())" :-))
My purpose was to avoid to hardcode an absolute directory to store a properties file, as well as to be sure that the directory returned does not change depending on how my application is started.
System.getProperty("user.dir") could not help because it returns the JVM start directory (the one from which you type the java command) :

C:\SCD\code>java -classpath . Test
System.getProperty("user.dir") = C:\SCD\code
C:\SCD\code>cd ..
C:\SCD>java -classpath code Test
System.getProperty("user.dir") = C:\SCD
I found a solution which seems to work well :
public static String getPathOfClass (Object classInstance) {
Class theClass = classInstance.getClass ();
String pathOfClass;
URL url = theClass.getResource (theClass.getName () + ".java");
try {
pathOfClass = new File ((new URI ("file://" + url)).getPath ()).getParent ();
}
catch (java.net.URISyntaxException e) {
pathOfClass = System.getProperty ("user.dir");
}
pathOfClass += File.separator;
return pathOfClass;
}
From my Test class main method, calling :
System.println("getPathOfClass(new Test()) = " + getPathOfClass(new Test()));
returns well my main class start path :
C:\SCD\code>java -classpath . Test
getPathOfClass(new Test()) = C:\SCD\code\
C:\SCD\code>cd ..
C:\SCD>java -classpath code Test
getPathOfClass(new Test()) = C:\SCD\code\
Any comment or suggestion of improvement will be appreciated.
Regards,
 
Philippe Maquet
Bartender
Posts: 1872
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please replace ".java" by ".class" in the preceding code...
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!