Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a file in WEB-INF/META-INF in a java web app?

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.

like image 828
Koray Tugay Avatar asked Jul 17 '14 19:07

Koray Tugay


People also ask

What is WEB-INF and META-INF?

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.

What is META-INF folder in Web application?

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.

What is META-INF file in Java?

The META-INF directory, if it exists, is used to store package and extension configuration data, including security, versioning, extension and services.

Where does the META-INF folder go?

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


2 Answers

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.

like image 74
Abhijeet Panwar Avatar answered Sep 20 '22 11:09

Abhijeet Panwar


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");
like image 25
user207421 Avatar answered Sep 19 '22 11:09

user207421