Writing text file using JSP is very simple to do in Java. With proper knowledge of what is required in result, form JSP to mark a text file is not very simple work.
Standard File Writing
• FileOutputStream section in java.io package is standard method to write data out to a file in OS. Constructor FileOutputStream will make new FileOutputStream pointing to filename précised by string.
• Standard PrintWriter section in java.io package offers simplest user-friendly technique of writing lines of data to an OutputStream. Constructor PrintWriter(OutputStream out) will make a new PrintWriter using available OutputStream. Mix this with FileOutputStream in below given instance:
FileOutputStream fos = new FileOutputStream("/var/log/mylog.txt");
PrintWriter pw = new PrintWriter(fos);
• For writing a line data to output stream, use PrintWriter's technique println(String x). This will write a line ended string of data to OutputStream.
• Completing writing to file, close together PrintWriter and FileOutputStream to launch related writing to file.
JSP-Specific Techniques
• Web application in JSP container, ServletContext.getReal and good quality of Path technique
• To implant logic in writing a file in JSP page, cover Java code in <% and %> and add page directive to import java.io.* classes.
• For writing a parameter passed to JSP page with request.getParameter technique in text file, use following:
<%@ page import="java.io.*" %>
<%
try {
String real_filename = context.getRealPath("/mylog.txt");
FileOutputStream fos = new FileOutputStream(real_filename);
PrintWriter pw = new PrintWriter(fos);
pw.println("This is a line of data");
pw.println(request.getParameter("test"));
pw.close();
fos.close();
}
catch (Exception e) {
// Handle exceptions
}
%>



Reply With Quote
Copyright Techfuels
Bookmarks