Java: getCodeBase() on non-applet application

2019-07-23 13:42发布

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

标签: java url applet
4条回答
做个烂人
2楼-- · 2019-07-23 14:07

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.
查看更多
放我归山
3楼-- · 2019-07-23 14:18

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");
查看更多
戒情不戒烟
4楼-- · 2019-07-23 14:20

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");
查看更多
成全新的幸福
5楼-- · 2019-07-23 14:20

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.

查看更多
登录 后发表回答