This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
I need to find and open a file from my code, but when I attempt it, it's not found. Using Eclipse to figure out where in the world I am (a Unix/Linux guy expects a "current working directory"), I find that
creates a file on the path ECLIPSE_HOME, which has nothing to do with my project location. I assume that if I generated a JAR with a main() inside (in fact, this is in some temporary test code inside a servlet I'm writing), it would create the file in the same directory as the JAR is located? Making the filename "/x.dat" creates it at the root of a Windows filesystem. Sure, I could put in manifest constants that help relate the file to my host's root, but isn't there a relative way?
Then I thought that there might be a way to expect to open a file proximal in some predictable way to the class files, sort of the way properties bundles are related to the package or class. However, I have yet to stumble upon a solution there.
I've Googled this sort of thing, but as you might imagine, the search string is prone to bring up a lot of irrelevant topics. Could someone point me to a tutorial, discussion, documentation, etc. treating this phenomenon. I spent too many years in C, I guess. Now I'm repenting, but I feel like a new guy sometimes when I come up against this sort of thing.
Officially it's not possible. However, there are a few tricks. I know two of these:
- using ProtectionDomain, as discussed here - using the class file as a resource: This URL is still not a file. You'll need to modify it:
- cut off the file name
- cut off the package folders
- if the URL is a JAR URL cut off the leading "jar:" part, and the "!" and the JAR file name
- transform the resulting "file:" URL into a File:
Note that this last trick will only work for class loaders that load from the file system. If the class / JAR file is loaded from a web server the URL will start with "http:" or "https:" (possibly prepended with "jar:"), and the conversion to File will fail.
As an example of what these class resource URLs can look like, try the following:
Just keep in mind that these trick are not guaranteed to work, especially not if the class isn't loaded from the local file system. I usually use a folder inside System.getProperty("user.home") for that. As an added benefit, each user can then have his/her own settings.