In my program, I am trying to read the file and then trying to overwrite the file using txtFile method. f is the file which I am reading and doing operations on its contents and now want to replace its contents with the new string, s.
String s = obj1.method(string);
toFile(s, f);
my txtFile method is below:
public static void txtFile(String cnvrt, File file)
{
try
{
PrintWriter printWriter = new PrintWriter (file);
printWriter.print(cnvrt);
printWriter.close ();
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
While doing this way, my original content is erased and the file gets empty. Please suggest me how to overwrite the same file using printWriter class? Even when I am using the FileWriter
and BufferedReader
, I obtained the empty file. Can somebody explain me this behavior?