[java] How Can I get the Absolute path at Runtime? Can I instead find out the Relative Path?

Started by
3 comments, last by zappsweden 18 years, 4 months ago
I am programming a game and want to be able to run it from anywhere on the harddrive (so I do not need to install it). I need to be able to read the images, sounds and other files that are relative to my main Class. I do not know how to use the relative path (without first finding out the absolute) so I must first find out the absolute path? The game determines its absolute path at runtime by creating a URL using the ClassName of my main Class. Here is the problem. It only works if there are no blank spaces (using Windows) in the path, since blank spaces obviously get thrown away when creating the URL. What to do? [Edited by - zappsweden on November 24, 2005 1:29:06 PM]
Advertisement
... uh?

Sorry, but I don't understand your question. In case you wish to find out at runtime what is the absolute path you're running on, you can print it out by calling:

System.out.println(new java.io.File("").getAbsolutePath());


If you wish to load resources using relative paths, you must add the resources' folder to the classpath. Then you use a String like "res/images/myImage.jpg" to retrieve an URL with:

MyClass.class.getResource("res/images/myImage.jpg");


If that's not what you want, sorry. I couldn't understand your question ;)

Son Of Cain
a.k.a javabeats at yahoo.ca
Try System.getProperty("user.dir");
> It only works if there are no blank spaces (using Windows) in the path, since blank spaces obviously get thrown away when creating the URL.

usually URLs are used if you get file from the net. If you get them from your hard drive just use the File class - it's not going to remove the spaces
Quote:Original post by Son of Cain
... uh?

Sorry, but I don't understand your question. In case you wish to find out at runtime what is the absolute path you're running on, you can print it out by calling:

System.out.println(new java.io.File("").getAbsolutePath());


If you wish to load resources using relative paths, you must add the resources' folder to the classpath. Then you use a String like "res/images/myImage.jpg" to retrieve an URL with:

MyClass.class.getResource("res/images/myImage.jpg");


If that's not what you want, sorry. I couldn't understand your question ;)

Son Of Cain


getAbsolutePath worked like a charm, THANKS dude :)

This topic is closed to new replies.

Advertisement