Java: getCodeBase() on non-applet application

2019-07-23 13:52发布

问题:

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).

回答1:

I would use the following to be relative to the working directory

URL myURL = new URL("file:somefile.txt");

or

URL myURL = new URL("file", "", "somefile.txt");

or

File file = new File("somefile.txt");


回答2:

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.

URL myURL = ClassLoader.getSystemResource("somefile.txt");


回答3:

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:

URL urlToText = this.getClass().getResource("/path/to/somefile.txt");

If it is read/write:

  • Check a known sub-directory of user.home for the file.
  • If not there, put it there (extracting it from a Jar).
  • Read/write to the file with known path.


回答4:

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.



标签: java url applet