[英]How load a txt file using ClassLoader?
I have the following code: 我有以下代码:
public class App {
public static void main(String[] args) {
System.out.println(App.class.getClassLoader().getResource("test.properties"));
System.out.println(App.class.getClassLoader().getResource("test.txt"));
System.out.println(App.class.getClassLoader().getResourceAsStream("test.properties"));
System.out.println(App.class.getClassLoader().getResourceAsStream("test.txt"));
System.out.println(App.class.getResourceAsStream("test.properties"));
System.out.println(App.class.getResourceAsStream("test.txt"));
}
}
This code gives the following output: 此代码提供以下输出:
file:/C:/../test.properties
null
java.io.BufferedInputStream@18e2b22
null
java.io.BufferedInputStream@1cb1c5fa
null
Why does ClassLoader refuses to load .txt file? 为什么ClassLoader拒绝加载.txt文件?
Updated: 更新:
I'm sure that both of my files in the classpath. 我确定我的两个文件都在classpath中。 Classpath is set to /src and both files are in this directory.
Classpath设置为/ src,两个文件都在此目录中。
很可能你的txt文件不在类路径上
You will need to ensure that any file you want to load using ClassLoader
is included in your classpath
. 您需要确保要使用
ClassLoader
任何文件都包含在classpath
。 Normally resources like that are stored in /src/main/resources
which is then included in the classpath. 通常,这样的资源存储在
/src/main/resources
,然后包含在类路径中。
If you're using Eclipse you can right click on the project in the explorer and go to Properties -> Java Build Path -> Source (Tab) -> Add Folder... (Button)
and add the folder structure in there. 如果你正在使用Eclipse,你可以右键单击资源管理器中的项目,然后转到
Properties -> Java Build Path -> Source (Tab) -> Add Folder... (Button)
并在其中添加文件夹结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.