how to write html form data to a text file using service class method called from controller servlet in java web application programming -
i learning java servlet programming.i have html form take pupil name , pupil age.this submitted controller saves info in context scoped attribute.then controller calls pupil service method save pupil record in text file in same folder class. works except service doesn't write record file.not sure going wrong. printed console service class method check if method invoked.i checked if exists , returns true. nil gets written file. tried fileoutputstream , filewriter classes both did not work. please help.
package service; import java.io.bufferedwriter; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.outputstreamwriter; public class studentservice { private file studentfile; public studentservice() { studentfile = "student.txt"; } public void savestudent(string studentname, int studentage) { bufferedwriter out = null; synchronized (studentfile) { seek { //system.out.println(studentfile.exists()); fileoutputstream fos = new fileoutputstream(studentfile); out = new bufferedwriter(new outputstreamwriter(fos)); out.write(studentname + "," + studentage + "\n"); } grab (ioexception e) { e.printstacktrace(); } { seek { if (out != null) { out.close(); } } grab (ioexception e) { // todo auto-generated grab block e.printstacktrace(); } } } }
you're assuming posted code write folder class is. that's not case @ all. write in current directory. current directory directory java command used start web container (tomcat, jetty, whetever) has been executed.
just like, when execute
ls foo.txt the ls programme lists attributes of foo.txt file in current directory.
use absolute path file:
public studentservice() { studentfile = "/foo/bar/student.txt"; } for curiosity, can know actual location of student.txt file doing
system.out.println(new file("student.txt").getabsolutepath()); java java-ee model-view-controller
No comments:
Post a Comment