简体   繁体   中英

web app java load resource from a file

I am on a dynamic web project, and I want to load a resource file.

I did this:

String queryTemplate = IOUtils.toString(this.getClass().getResource(
                "test.rq"));

where test.rq exist in src/main/resources , but i got null pointer for on that line.

I thought maybe that src/main/resources is not the main (default) resource folder in maven, so i put this in the pom

<build>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>

        </resources>
    </build>

but then my asp pages stopped working (i don't know why), so I think that there is a way to get that resources from the src/main/resources without changing the pom

Use this:

InputStream testIn = getClass().getResourceAsStream("/test.rq");
String queryTemplate = IOUtils.toString(testIn);

IOUtils.toString() appears to take an InputStream as input, so I used getResourceAsStream() .

My guess as to the null pointer is that you need to refer to the root of your classpath to access the resource file, hence I used /test.rq , where the slash means root.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM