John Eipe
John Eipe

Reputation: 11228

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)

Upvotes: 1

Views: 1849

Answers (1)

BalusC
BalusC

Reputation: 1108722

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>

Upvotes: 3

Related Questions