[英]How do I use the file from classpath?
I need help getting a file from a file to use it.我需要帮助从文件中获取文件才能使用它。 The file is specified in the -cp option when running jar through the console.当通过控制台运行 jar 时,该文件在 -cp 选项中指定。
run the jar using:使用以下命令运行 jar:
java -cp myjar.jar:dir1/dir2/myfile.txt com.company.Main
execution result:执行结果:
Exception in thread "main" java.lang.NullPointerException
at com.company.Main.main(Main.java:11)
source code:源代码:
package com.company;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
ClassLoader classLoader = Main.class.getClassLoader();
InputStream resource = classLoader.getResourceAsStream("dir1/dir2/myfile.txt");
System.out.println(resource.toString());
}
}
project tree项目树
-- сom
---- company
------ Main.java
How do I get that file from -cp?如何从 -cp 获取该文件?
Since you specify dir1/dir2/myfile.txt
in the getResourceAsStream()
call, you want the directory containing dir1
on the classpath, which would be the working directory , ie .
由于您在getResourceAsStream()
调用中指定了dir1/dir2/myfile.txt
,因此您需要在类路径上包含dir1
的目录,这将是工作目录,即.
: :
java -cp myjar.jar:. com.company.Main
The classpath can only specify:类路径只能指定:
No other type of file is supported.不支持其他类型的文件。
It appears that your computer cannot find the file.您的计算机似乎找不到该文件。 Right click on the file and select explorer to see the path or if you are using intellij idea you will see an option to copy the path when you right click on it.右键单击文件并选择资源管理器以查看路径,或者如果您使用的是 intellij idea,当您右键单击它时,您将看到一个复制路径的选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.