I'm trying to create a URL to access a local file like so:
URL myURL = new URL(getCodeBase(), "somefile.txt");
But it throws a NullPointerException when it attempts getCodeBase(). I'm fairly certain that the reason behind this is because the class file that this code belongs to is not an applet. Is there any way I can get the code base without using an applet? I just want to access a local file without having to put the actual directory in (because when others run the application the directory path will obviously not be the same).
If
somefile.txt
is read-only, put it in a Jar that is on the run-time class-path of the application. Access it using:If it is read/write:
user.home
for the file.You don't need to get the code base. If the file resides on your classpath (this includes the path where your classes are deployed), you can access vía the ClassLoader method getSystemResource.
I would use the following to be relative to the working directory
or
or
See How to create a folder in Java posting, which asked very similar question.
As Tomas Narros said above, the proper way to do this is to use the ClassLoader to locate resource files in the Classpath. The path you pass to the ClassLoader is relative to the classpath that was set when you started the Java app.
If you browse the above link, you'll see some sample code showing how to resolve the path to a file in your classpath.