Monday, March 10, 2008

Technical: To Solve Relative FilePath on Servlets

This will solved the issue of using a relative path in the servlet.

Snippet of the Servlet
ReadFromFile.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ReadFromFile extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

res.setContentType("text/html");

ServletOutputStream out = res.getOutputStream();
out.println("<html>");
out.println("<head><title>Read From File</title></head>");
out.println("<body>");

// print the file
InputStream in = null;
try {
in = new BufferedInputStream
/**
* I placed this servlet at $TOMCAT/webapps/ROOT/WEB-INF/classes/
* The code "req.getRealPath" will point u to $TOMCAT/webapps/ROOT
* So I create another folder called library under ROOT, and place my test.txt inside.
*/
(new FileInputStream(req.getRealPath("/library/test.txt")) );
int ch;
while ((ch = in.read()) !=-1) {
out.print((char)ch);
}
}
finally {
// close the InputStream
if (in != null) in.close();
}
out.println("</body></html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletExceptio
{
doGet(request, response);
}
}

No comments: