Last updated on November 16th, 2015 at 09:51 am

In Java we can write a Servlet that can be used to read any file by providing its absolute path and display its content in a web browser. You can modify the script according to your needs.

This script can be used for text files, shell scripts, log files etc., any file that can be viewed using a CAT command in linux.

Below i have created a class with the name view, All you have to do is compile the java code and run the URL with query string that contains the absolute path of the file you want to read.
My mapping looks like this

<servlet>
    <servlet-name>view</servlet-name>
    <servlet-class>view</servlet-class>
  </servlet>
<servlet-mapping>
    <servlet-name>view</servlet-name>
    <url-pattern>/view.read</url-pattern>
  </servlet-mapping>
<servlet>

My view.java file looks like this

import java.io.* ;
import javax.servlet.http.* ;

public class view extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
String path = request.getParameter("path");
PrintWriter out = response.getWriter();
out.println("<html><title>File Viewer</title><body><h2>Viewing File "+path+"</h2><p>");
try
{
BufferedReader in = new BufferedReader(new FileReader(path));
String str;
while ((str = in.readLine()) != null) {
out.println(str+"<br>");
}
in.close();
out.println("</body></html>");
}
catch(Exception e)
{
System.out.println( "cannot get reader: " + e );
}
}
}

For example if you have file named check.txt in the path /usr/local/, then the URL will be http://somewebsite/view.read?path=/usr/local/check.txt

Since this is a tutorial i have provided GET parameter. It is highly recommended to have a POST request so that the values are not visible.

Leave a Reply

Your email address will not be published. Required fields are marked *