Reputation: 97
I have created a file from the doPost Method in servlet but I am unable to write the data to it. I could not figured out what is the error. By the way the file is creating
// TODO Auto-generated method stub
response.setContentType("text/html");
String name=request.getParameter("name");
response.getWriter().println(name);
File filename= new File("/home/ksampath/D3/DedupeEngine/cache3.txt");
filename.createNewFile();
BufferedWriter out = null;
try
{
System.out.println("I am going to create a new file");
FileWriter fw=new FileWriter("cache3.txt",true);
out=new BufferedWriter(fw);
out.write("hello world");
out.write(name);
}
catch(IOException e)
{
System.err.println("Error"+ e.getMessage());
}
finally
{
if(out!=null)
{
out.close();
}
}
/*
System.out.println("Lets us check whether it works");
PrintWriter writer=response.getWriter();
writer.println("<h3>hello This is my first servlet</h3>");*/
}
Upvotes: 0
Views: 40
Reputation: 2515
Solution provided by @singhakash is correct.
You can either use
FileWriter fw=new FileWriter(filename,true);
and as stated that if second argument is true than bytes will be appended at end.
or you can use getAbsoluteFile()
method of File, in this way
FileWriter fw=new FileWriter(filename.getAbsoluteFile());
The
getAbsoluteFile()
method will return, The absolute abstract pathname denoting the same file or directory as this abstract pathname(JavaDocs)
Upvotes: 1
Reputation: 7919
Try
FileWriter fw=new FileWriter(filename,true); //where filename is that File object
public FileWriter(File file, boolean append) throws IOException
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Upvotes: 1