Dmitry D
Dmitry D

Reputation: 760

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?

Updated:

I'm sure that both of my files in the classpath. Classpath is set to /src and both files are in this directory.

Upvotes: 1

Views: 4319

Answers (2)

Deco
Deco

Reputation: 3321

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.

Upvotes: 1

henry
henry

Reputation: 6096

Most likely your txt file is not on the classpath

Upvotes: 2

Related Questions