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...

Java File Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.