Java: getCodeBase() on non-applet application

廉价感情. 提交于 2019-12-13 15:25:03

问题


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.



来源:https://stackoverflow.com/questions/8714294/java-getcodebase-on-non-applet-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!