View RSS Feed

My Java Tips

Writing a file from JSP

Rate this Entry
by , 05-24-2011 at 01:45 PM (7227 Views)
You may want to write a file from JSP page. For example, user fills a form and you want to persist the details on a text file on server. Now you need to know how to write text file from JSP.

Remember, always give the path from root. In the given snippet, nameOfTextFile contains the file path. We will use FileOutputStream to write to the file.

Java Code:
<%@ page import="java.io.*"  %>
<%
String str = "form data goes here";
String nameOfTextFile = "/usr/resources/data.txt";
try {   
    PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
    pw.println(str);
    pw.close();
} catch(IOException e) {
   out.println(e.getMessage());
}
%>

Submit "Writing a file from JSP" to Facebook Submit "Writing a file from JSP" to Digg Submit "Writing a file from JSP" to del.icio.us Submit "Writing a file from JSP" to StumbleUpon Submit "Writing a file from JSP" to Google

Categories
JSP

Comments