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.
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.
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");
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");
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.