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.
The META-INF directory is private and can't be accessed from the outside. On the other hand, it also contains the WEB-INF public directory with all the static web resources, including HTML pages, images, and JS files. Moreover, it contains the web. xml file, servlet classes, and libraries.
The META-INF folder is the home for the MANIFEST. MF file. This file contains meta data about the contents of the JAR. For example, there is an entry called Main-Class that specifies the name of the Java class with the static main() for executable JAR files.
The META-INF directory, if it exists, is used to store package and extension configuration data, including security, versioning, extension and services.
Basically it has to be in your classpath(under /META-INF/ ). You can manually enable it in eclipse by configuring properties. If your project is maven based, then it should be automatically picked from /src/main/resources/META-INF/ folder (provided entities are under the same hood).
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With