In Java, we can append a string in an existing file using FileWriter which has an option to open a file in append mode. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in Java. Unlike FileOutputStream class, we don’t need to convert the string into a byte array because it provides a method to write a string directly.
Note: The buffer size may be specified, or the default size may be used. A Writer sends its output immediately to the underlying character or byte stream.
Let us see constructors used later on adhering towards as usual methods of this class
Constructor: FileWriter(File file, boolean append):
It Constructs a FileWriter object given a File object in append mode. Now let us toggle onto methods of this class which is invoked here and play a crucial role in appending a string in an existing file as follows:
Method 1: write()
This method writes a portion of a String
Syntax:
void write(String s,int off,int len);
Return Type: Void
Parameters:
- Input string
- int off
- String length
Method 2: close()
This method closes the stream after flushing it.
Return Type: Void
Example
Java
import java.io.*;
class GeeksforGeeks {
public static void appendStrToFile(String fileName,
String str)
{
try {
BufferedWriter out = new BufferedWriter(
new FileWriter(fileName, true ));
out.write(str);
out.close();
}
catch (IOException e) {
System.out.println( "exception occurred" + e);
}
}
public static void main(String[] args) throws Exception
{
String fileName = "Geek.txt" ;
try {
BufferedWriter out = new BufferedWriter(
new FileWriter(fileName));
out.write( "Hello World:\n" );
out.close();
}
catch (IOException e) {
System.out.println( "Exception Occurred" + e);
}
String str = "This is GeeksforGeeks" ;
appendStrToFile(fileName, str);
try {
BufferedReader in = new BufferedReader(
new FileReader( "Geek.txt" ));
String mystring;
while ((mystring = in.readLine()) != null ) {
System.out.println(mystring);
}
}
catch (IOException e) {
System.out.println( "Exception Occurred" + e);
}
}
}
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!