How to append a string in an existing file in java

  • by

In the following section of code shows how to append a string in an existing file. It can be append a string in an existing file using FileWriter() method. The boolean parameter in method indicates true if you want the append functionality which is primary objective to append strings of characters in the existing file.

Append a string in an existing file:-
import java.io.*;
public class Main
{
public static void main(String[] args) throws Exception
{
try
{

BufferedWriter out = new BufferedWriter (new FileWriter(“filename”));
out.write(“aStringI\n”);
out.close();
out = new BufferedWriter(new FileWriter(“filename”,true));
out.write(“aStringII”);
out.close();
BufferedReader in = new BufferedReader (new FileReader(“filename”));
String str;
while ((str = in.readLine()) != null)
{
System.out.println(str);
}
}
in.close();

catch (IOException e)
{
System.out.println(“exception occoured”+ e);
}
}
}

Leave a Reply