[英]How to specify the directory as classpath in order to read a file in it using classloader while running java application?
Let's say there is a file abc.txt
present in directory dir
. 假设目录
dir
存在文件abc.txt
。 I am trying to run a java application using following command java -cp dir;myjar.jar com.example.Main
我正在尝试使用以下命令运行Java应用程序
java -cp dir;myjar.jar com.example.Main
And in Main class, I am trying to access this file like this getClass().getResource("/abc.txt")
. 在Main class中,我试图像
getClass().getResource("/abc.txt")
这样访问此文件。 But this is returning null. 但这返回null。 I am not sure what's wrong here.
我不确定这是怎么回事。 Any pointers will be appreciated.
任何指针将不胜感激。
Since the file is in the root of the classpath directory, you need to use "/abc.txt"
, otherwise it's looking in the package folder for the class in question. 由于该文件位于classpath目录的根目录中,因此您需要使用
"/abc.txt"
,否则它将在package文件夹中查找有问题的类。
Just like the javadoc of getResource
says: 就像
getResource
的javadoc一样:
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
在委派之前,使用以下算法从给定资源名称构造绝对资源名称:
If the
name
begins with a'/'
('\/'
), then the absolute name of the resource is the portion of thename
following the'/'
.如果
name
与开始'/'
('\/'
),则资源的绝对名称是所述的部分name
之后的'/'
。Otherwise, the absolute name is of the following form:
否则,绝对名称的格式如下:
modified_package_name/name
Where the
modified_package_name
is the package name of this object with'/'
substituted for'.'
其中
modified_package_name
是此对象的软件包名称,用'/'
代替'.'
('\.'
).(
'\.'
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.