Java program to append text to an existing file
Here's a Java program that appends text to an existing file:
import java.io.*; public class FileAppend { public static void main(String[] args) { String fileName = "example.txt"; String textToAppend = "This text will be appended to the end of the file."; try { FileWriter fileWriter = new FileWriter(fileName, true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); PrintWriter printWriter = new PrintWriter(bufferedWriter); printWriter.println(textToAppend); printWriter.close(); System.out.println("Text has been appended to the file."); } catch (IOException e) { System.out.println("An error occurred: " + e); } } }Source:www.theitroad.com
In this program, we define a String
variable fileName
to hold the name of the file we want to append to, and a String
variable textToAppend
to hold the text we want to append.
We then create a FileWriter
object to write to the file. We pass true
as the second argument to the FileWriter
constructor, which means that we want to append to the file instead of overwriting it.
Next, we create a BufferedWriter
object and pass it the FileWriter
object as an argument. We then create a PrintWriter
object and pass it the BufferedWriter
object as an argument.
Finally, we use the println
method of the PrintWriter
object to append the text to the file, and we close the PrintWriter
object. We also print a message to the console to indicate that the text has been appended to the file.
Note that this program assumes that the file already exists. If the file does not exist, this program will throw an exception. You can add additional code to handle this situation as needed.