Write a java program to Append text or string in a file


This Java code defines a class FileAppend with a main method that appends a string "Welcome Java" to a file named "file.txt" in the current working directory. The try block creates a new FileOutputStream object with a filename "file.txt" and a boolean flag true, which indicates that data should be appended to the file rather than overwriting it.

The string "Welcome Java" is then converted to a byte array using the getBytes method of the String class, and the resulting byte array is written to the file using the write method of the FileOutputStream class.

Finally, the program closes the file using the close method of the FileOutputStream class and prints out a message indicating that the string was successfully appended to the file.

Note that this code assumes that the file "file.txt" exists in the current working directory, and will throw a FileNotFoundException if the file cannot be found.

Source Code

import java.io.*;
public class FileAppend
{
	public static void main(String[] args)
	{
		String str_file = "file.txt";
		try
		{
			//file output stream to open and write data
			FileOutputStream f = new FileOutputStream(str_file, true);
 
			String strContent = "Welcome Java";//appended string
 
			f.write(strContent.getBytes());//appending string
			f.close();
			System.out.println("String Append Successfully ...");
		}
		catch (FileNotFoundException f)
		{
			System.out.println("FileNotFoundException : " + f.toString());
		}
		catch (IOException i)
		{
			System.out.println("IOException : " + i.toString());
		}
		catch (Exception e)
		{
			System.out.println("Exception: " + e.toString());
		}
	}
}

Output

String Append Successfully ...