thiru thiru - 4 months ago 13
Java Question

how to write html form data to a text file using service class method called from controller servlet in java web application programming

I am learning Java servlet programming.I have HTML form to accept student name and student age.This is submitted to a controller which saves the data in a context scoped attribute.Then controller calls a student service method to save the student record in a text file which is in the same folder as the class. Everything works except the service doesn't write the record to the file.Not sure where i am going wrong. I printed to the console from the service class method to check if the method is invoked.I checked if the exists and it returns true. but nothing gets written to the file. I tried FileOutputStream and FileWriter classes but both did not work. Please could somebody 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) {
try {
//System.out.println(studentFile.exists());
FileOutputStream fos = new FileOutputStream(studentFile);
out = new BufferedWriter(new OutputStreamWriter(fos));
out.write(studentName + "," + studentAge + "\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Answer

You're assuming that the posted code will write to the folder where the class is. That's not the case at all. It will write in the current directory. The current directory is the directory from which the java command used to start the web container (tomcat, jetty, whetever) has been executed.

Just like, when you execute

ls foo.txt

the ls program lists the attributes of the foo.txt file in the current directory.

Use an absolute path for the file:

public StudentService() {
    studentFile = "/foo/bar/student.txt";
}

For your curiosity, you can know what the actual location of the student.txt file is by simply doing

System.out.println(new File("student.txt").getAbsolutePath());
Comments