Java:非 applet 应用程序上的 getCodeBase()
我正在尝试创建一个 URL 来访问本地文件,如下所示:
URL myURL = new URL(getCodeBase(), "somefile.txt");
但当它尝试 getCodeBase() 时,它会抛出 NullPointerException。我相当确定这背后的原因是因为该代码所属的类文件不是小程序。有什么方法可以在不使用小程序的情况下获取代码库吗?我只想访问本地文件,而不必放入实际目录(因为当其他人运行应用程序时,目录路径显然会不一样)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我将使用以下相对于工作目录
或
或
I would use the following to be relative to the working directory
or
or
您不需要获取代码库。
如果该文件位于类路径上(这包括部署类的路径),则可以通过 ClassLoader 方法 getSystemResource。
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.
如果
somefile.txt
是只读的,请将其放入应用程序运行时类路径上的 Jar 中。使用以下方式访问它:如果是读/写:
user.home
的已知子目录中是否有该文件。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.请参阅如何创建文件夹在 Java 发布中,它提出了非常相似的问题。
正如 Tomas Narros 上面所说,正确的方法是使用 ClassLoader 在 Classpath 中定位资源文件。您传递给 ClassLoader 的路径与启动 Java 应用程序时设置的类路径相关。
如果您浏览上面的链接,您将看到一些示例代码,显示如何解析类路径中文件的路径。
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.