Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to get absolute path for a class file 2

Status
Not open for further replies.

fechen

Technical User
Jan 25, 2002
48
0
0
US
In Java, how can I get the absolute path for a class file programatically?

One simple example will be: say I have test.class file, if I put it in C:\temp\, run it from anywhere, it will print out C:\temp. If I put it into C:\program files\test\, it prints out the above path, too.
In VC++ and VB, there is methods to do that, but I can not find a way to do in Java so far.

Maybe this concept is not cross-platform? so java don't have this at all?

Java experts please help. Thanks.
 
Code:
File f = new File(".");
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());
 
Well, this is not what I want.

The code will return whatever the current dir is, not the location of the class file.

The problem is a user can start a class from anywhere. I am looking for a way to find the location of the class.

More specific, let's say my class is C:\temp\Test.class,
if I go to D:\, issue "java -classpath C:\temp Test", I'd like to have "C:\temp" or "C:\temp\Test.class" returned.
 
Try this:

Code:
import java.net.*;

class Tester
{
   public Tester()
   {
      ClassLoader cl = this.getClass().getClassLoader();
      URL u = cl.getResource("Tester.class");
      System.err.println("Url=" + u);
   }

   public static void main( String[] args )
   {
      Tester t = new Tester();
   }
}
 
Got it working. Thanks a lot, idarke.
 
One more question.

I have following code, based on idarke's:

ClassLoader cl = ClassLoader.getSystemClassLoader();
URL url = cl.getResource(".");
File theFile = new File(url.getFile());
System.out.println(theFile.getPath());


If the current dir doesn't have space char, it works good.
If it has a space char, then it returns
C:\src%20code
My question, how can I get rid of this "%20"

Thanks,

 
One more question.

I have following code, based on idarke's:

ClassLoader cl = ClassLoader.getSystemClassLoader();
URL url = cl.getResource(".");
File theFile = new File(url.getFile());
System.out.println(theFile.getPath());


If the current dir doesn't have space char, it works good.
If it has a space char, then it returns
C:\src%20code
My question: how can I get rid of this "%20"

Thanks,

 
Use java.net.URLEncoder to decode it.

e.g.

System.out.println(URLEncoder.decode(theFile.getPath()));

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top