Saturday, 17 August 2013

Writing to a text file by a method that takes in a string parameter

Writing to a text file by a method that takes in a string parameter

H guys, I'm trying to pass in a string parameter to write that string to a
text file. However, I seem to be having trouble.
It works fine when I compile it in a main method, it creates a file and
all the values that i write into it.
However, when I use a method. It doesn't create a file at all, not even
with the parameters that I passed in . I am intending to use the method in
a Servlet.
Below is the method that i created.
public class testWriteFile {
public static void writeToFile (String data) throws Exception
{
Date dateNow = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
StringBuilder formatDDMMYYYY = new StringBuilder(sdf.format(dateNow));
File file = new File(formatDDMMYYYY+".txt");
if(!file.exists())
{
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");
}
}
May I know what is the problem with the code? Thanks in advance!

No comments:

Post a Comment