简体   繁体   English

如何在运行Java应用程序时使用classloader将目录指定为classpath以读取其中的文件?

[英]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 the name 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.

相关问题 将相对目录添加到java类路径并使用ClassLoader()。getResourceAsStream(“”) - adding relative directory to java classpath and using ClassLoader().getResourceAsStream(“”) 运行Java应用程序时如何将classpath放在属性文件中? - How can I put classpath in property file while running java application? 如何使用Java ClassLoader从类路径加载文件? - How do I use the Java ClassLoader to load a file fromthe classpath? JAR不在类路径上,强制类加载器从其读取文件 - JAR not on classpath, force classloader to read file from it 如何使用Ant构建jar文件时设置classpath顺序? - How to set classpath order while building jar file using Ant? 如何获取在 webstart 上运行的 Java 应用程序的类路径? - How to get the classpath of a Java application running on webstart? 在制作Android应用程序时如何使用JAVA读取文件 - How to read a file using JAVA while making Android Application 如何在将文件移动到Java中的另一个目录时为文件指定新名称? - How to specify a new name for a file while moving it to another directory in Java? 如何使用Apache Ant将目录或文件glob指定为javac类路径值? - How to specify directory or file glob as javac classpath value with Apache Ant? 如何在JAR清单文件中指定类路径的加载顺序 - How to specify classpath loading order in a JAR manifest file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM