Reputation:
I am currently writing a game, titled Legend of Zork (development title), mostly to keep me busy writing code and learning Java on a deeper level. I am stuck on a particular task, however.
I wish to be able to copy the containing folder to anywhere on my computer, someone else's computer, or even a flash drive, and have it functioning. When I compile the program into a Jar, I would need to specify the path to the folder so the code could use the required files (for instance, music or spreadsheets). I have attempted the following:
String dir = System.getProperty("user.dir") + "/resources/";
which will give the proper path within Eclipse ("/media/MOTHLACHAIN/LegendOfZork/resources/", which is the thumb drive I use as my workspace) and runs perfectly, but when I build and run the jar, it will not run due to FileNotFoundException. In terminal, typing "java -jar LegendOfZork.jar", which works if I do not include the class referring to a file, says that it is looking for "/home/viktor/resources/Weapons.xls" when it should be looking for "/home/viktor/LegendOfZork/resources/Weapons.xls", or if running from my desktop, should be looking for "/home/viktor/Desktop/LegendOfZork/resources/Weapons.xls" and so on.
My program's folder hierarchy is:
1. LegendOfZork
- audio
- music
- sounds
- bin
- resources
The LegendOfZork folder would be where the jar file is contained, wherever I'd want to put the program, and the resources would be where I'd want to access a spreadsheet, for instance.
Any help would be much appreciated. Thank you much in advanced!
Upvotes: 0
Views: 131
Reputation: 347334
Try using...
File file = new File(".");
Which will get you a reference to the current working directory.
If you need to know the absolute path then use something like ...
file.getAbsoluteFile();
or
file.getCanonicalFile()
See the JavaDocs for more details
Now, File
allows you to define relative paths. So something like File resources = new File("resources");
will create an abstract path for ./resources
. Now, this is obviously relative to the point of execution (where the program was run from), so you may need to take that into account.
So assuming you folder hirarcy looks something like..
+ LegendOfZork
...jar files...
+ audio
+ music
+ sounds
+ bin
+ resources
For example, and you application was launched from the context of the LegendOfZork
directory, then to get access to the audio
directory, you would need to do something like...
File audio = new File("../audio");
File music = new File(audio, "music");
File sounds = new File(audio, "sounds");
For example...
Upvotes: 1
Reputation: 151
To get the current directory, just use something like this:
public class CurrentPath extends java.io.File
{
private static String path = ".";
CurrentPath()
{
super(path);
}
String getResult()
{
return path;
}
public static void main(String[] args)
{
CurrentPath cpp = new CurrentPath();
//get path with cpp.getResult();
}
}
Upvotes: 0