Java:非小程序应用程序上的 getCodeBase() [英] Java: getCodeBase() on non-applet application

查看:28
本文介绍了Java:非小程序应用程序上的 getCodeBase()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 URL 来访问本地文件,如下所示:

I'm trying to create a URL to access a local file like so:

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

但是当它尝试 getCodeBase() 时会抛出 NullPointerException.我相当肯定这背后的原因是因为这段代码所属的类文件不是小程序.有什么方法可以在不使用小程序的情况下获得代码库吗?我只想访问本地文件,而不必将实际目录放入(因为当其他人运行应用程序时,目录路径显然不一样).

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

推荐答案

我会使用以下相对于工作目录

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

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

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

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

这篇关于Java:非小程序应用程序上的 getCodeBase()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆