This example will show you how to write the data provided by the user into a text file.
Step 1 : Create HTML or JSP page to accept user input.
Enter the following code in the body tag of your code
<form action="servlet1">
Name : <input type="text" name="username"/>
<br/>
Email ID : <input type="text" name="email"/>
<br/>
<input type="submit" value="OK"/>
</form>
Step 2 : Retriving User input values and writing it into a text file.
Enter the following code in the doGet() of the servlet (in my case named "servlet1").
//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.
//retriving & storing user input in the String Variables
String name = request.getParameter("username");
String eid = request.getParameter("email") ;
//writing data into a text file
PrintWriter pw = null;
try {
pw= new PrintWriter(new FileWriter("D:\\file.txt", true)); //the second parameter of the file writer object accepts a boolean value to specify whether to append to existing file (true) or to overwrite the existing file (false).
pw.print(name + "\t");
pw.println(eid);
pw.close();
}
catch (IOException ex) { //exception handling code }
finally {
pw.close();
}
Finally, check the file from the path where it has been created.
No comments:
Post a Comment