Reputation: 23854
So the book I am reading says:
Unlike JAR files, the root-level /META-INF directory is not on the application classpath. You cannot use the ClassLoader to obtain resources in this directory. /WEB-INF/classes/META-INF, however, is on the classpath. You can place any application resources you desire in this directory, and they become accessible through the ClassLoader.
And currently under WEB-INF directory I have a META-INF directory and a file called: test.txt.
How can I read this file using the ClassLoader ?
I have tried this:
URL resource = this.getClass().getClassLoader().getResource("test.txt");
System.out.println(resource);
But this returns null.
I know the file can be read like:
InputStream resourceContent = getServletContext().getResourceAsStream("/WEB-INF/META-INF/test.txt");
System.out.println(resourceContent);
but this is not I want. I want to understand the ClassLoader..
Thanks.
Upvotes: 9
Views: 8561
Reputation: 92
If you put the text file right inside your WEB-INF, you could do this,
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("../test.txt");
In your case, since your text file is inside the META-INF folder which is inside WEB-INF, you can access the text file like so,
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("../META-INF/test.txt");
Upvotes: 0
Reputation: 1867
Try using this:
URL resource=this.getClass().getClassLoader().getResource("META-INF/test.txt");
as your /META-INF is in your root path you will have to use META-INF/test.txt to access it.
Upvotes: 8
Reputation: 311054
And currently under WEB-INF directory I have a META-INF directory
Then you've done it wrong. Read your own quotation. It says WEB-INF/classes/META-INF.
URL resource = this.getClass().getClassLoader().getResource("test.txt");
That should be:
URL resource = this.getClass().getClassLoader().getResource("META-INF/test.txt");
Upvotes: 4