Java | Appending String to a File
In Java we can append a string in an existing file using FileWriter which has an option to open file in append mode.
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in Java. Unlike FileOutputStream class, we don’t need to convert string into byte array because it provides method to write 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.
Class constructor used:
FileWriter(File file, boolean append) – constructs a FileWriter object given a File object in append mode.
Class methods used:
void write(String s, int off, int len)
This method writes a portion of a String.
void close()
This method closes the stream after flushing it.
// Java program to append a string to the // end of a file. import java.io.*; public class GeeksforGeeks { public static void appendStrToFile(String fileName, String str) { try { // Open given file in append mode. BufferedWriter out = new BufferedWriter( new FileWriter(fileName, true)); out.write(str); out.close(); } catch (IOException e) { System.out.println("exception occoured" + e); } } public static void main(String[] args) throws Exception { // Let us create a sample file with some text 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); } // Let us append given str to above // created file. String str = "This is GeeksforGeeks"; appendStrToFile(fileName, str); // Let us print modified file 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); } } } |

Recommended Posts:
- Java | Renaming a file
- Delete a file using Java
- Java Class File
- File Permissions in Java
- Java.io.File Class in Java
- Check if a File is hidden in Java
- How to run java class file which is in different directory?
- Myth about the file name and class name in Java
- Copying file using FileStreams in Java
- Writing a CSV file in Java using OpenCSV
- How to play an Audio file using Java
- Moving a file from one directory to another using Java
- Reading a CSV file in Java using OpenCV
- Size of file on the Internet using Java
- File delete() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



