问题描述
我试图创建一个URL来访问本地文件,像这样:
I'm trying to create a URL to access a local file like so:
URL myURL = new URL(getCodeBase(), "somefile.txt");
但是,当它试图得到codeBase的(),它抛出一个NullPointerException异常。我相当肯定,这背后的原因是因为这code属于类文件不是一个小程序。有什么办法,我可以得到code碱基不使用小程序?我只是想访问本地文件,而无需把实际的目录中(因为当别人运行应用程序的目录路径显然不会是相同的)。
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的:得到codeBase的()在非小程序应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!