Home » Java programs » Java file handling programs

Java program to append text/string in a file

In this java program, we are going to learn how to append text/string in a given file? Here, we have a file with some pre written content and we are appending text in it.
Submitted by IncludeHelp, on October 19, 2017

Given a file and we have to append text/string in the file using java program.

There is a file named "IncludeHelp.txt" which is stored at my system in "E:" drive under "JAVA" folder (you can choose your path), and file contains the following text,

This is sample text.

Example:

File’s content: "This is sample text."
Text to append: "Text to be appended."
File’s content after appending: "This is sample text.Text to be appended."

Consider the program

import java.io.*;
 
public class AppendFile 
{
  public static void main(String[] args)
   {  
	 //file name with path
     String strFilePath = "E:/JAVA/IncludeHelp.txt";
     try
     {
    	//file output stream to open and write data
        FileOutputStream fos = new FileOutputStream(strFilePath, true);
        //string to be appended
        String strContent = "Text to be appended.";
        
        //appending text/string
        fos.write(strContent.getBytes());
        //closing the file
        fos.close();        
        System.out.println("Content Successfully Append into File...");        
     }
     catch(FileNotFoundException ex)
     {
      System.out.println("FileNotFoundException : " + ex.toString());
     }
     catch(IOException ioe)
     {
      System.out.println("IOException : " + ioe.toString());
     }
     catch (Exception e)
     {
    	 System.out.println("Exception: " + e.toString());
     }
   }
}

Output

Content Successfully Append into File...





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.