简体   繁体   中英

How to read file from outside web content directory

I have the following scriptlet inside a JSP page.

  File f = new File("//WEB-INF//music//rock//Evanascence//Fallen//text.txt");
  FileReader fr = new FileReader(f);
  out.println(f.exists());

I'm getting a

FileNotFoundException: \\\\WEB-INF\\music\\rock\\Evanascence\\Fallen\\text.txt (The network path was not found)

You shouldn't use the File API to reference relative webcontent files. The File API operates relative to the current working directory on the local disk file system, which is dependent on how you started the webserver and is in no way controllable from inside the webapplication's code.

In this particular case you should rather use ServletContext#getResource() or getResourceAsStream() :

URL resource = getServletContext().getResource("/WEB-INF/music/rock/Evanascence/Fallen/text.txt");
// ...

or

InputStream input = getServletContext().getResourceAsStream("/WEB-INF/music/rock/Evanascence/Fallen/text.txt");
// ...

(note that those double forward slashes are totally unnecessary, I already removed them)

If it returns null then it don't exist. To wrap it in a Reader , use InputStreamReader wherein you specify the proper character encoding which should be the same as the file is originally saved in:

Reader reader = new InputStreamReader(input, "UTF-8");
// ...

See also:


Unrelated to the concrete question, needless to say that the code above belongs in a servlet , not in a JSP as you tagged. Inside a JSP, you may find the JSTL 's <c:import> tag more useful.

<c:import url="/WEB-INF/music/rock/Evanascence/Fallen/text.txt" />

Or if it is possibly non-existing:

<c:catch var="e">
    <c:import url="/WEB-INF/music/rock/Evanascence/Fallen/text.txt" var="text" />
</c:catch>
<c:choose>
    <c:when test="${empty e}">
        <pre><c:out value="${text}" /></pre>
    </c:when>
    <c:otherwise>
        <p>An exception occurred when reading file: <pre>${e}</pre></p>
    </c:otherwise>
</c:choose>

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