Read file under WEB-INF directory example 2016-08-25 05:56

For JavaEE project you can request the file under project directory except the file under WEB-INF. Put the file under WEB-INF directory if you do not want others to access it informally. The question is how to access it in project. This blog will show you how to access the file under WEB-INF directory programmatically.

Project structure

│  ├─java
│  │  └─com
│  │      └─henryxi
│  │          └─resource
│  │        
│  │
│  ├─resources
│  │      spring-all.xml
│  │
│  └─webapp
│      │  index.jsp
│      │
│      └─WEB-INF
│              target_file.txt
│              web.xml

public class SimpleController {
    private ResourceLoader resourceLoader;

    public String testProperties() throws IOException {
        String content = IOUtils.toString(resourceLoader.getResource("/WEB-INF/target_file.txt").getInputStream());
        return "the content of resources:" + content;

Start this project and access localhost:8080/WEB-INF-file you will get the result as following.

the content of resources:This is the file in the directory /WEB-INF/target_file.txt.

The most important part of code is resourceLoader.getResource("/WEB-INF/target_file.txt"). This line means read the file target_file.txt by using resourceLoader. In order to show the content you can convert the input stream to string or write the content to response directory. (I choose the former approach)