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?
Updated:
I'm sure that both of my files in the classpath. Classpath is set to /src and both files are in this directory.
很可能你的txt文件不在类路径上
You will need to ensure that any file you want to load using ClassLoader
is included in your classpath
. Normally resources like that are stored in /src/main/resources
which is then included in the classpath.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.