Q:

Java program to append text/string in a file

belongs to collection: Java File Handling Programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to determine number of bytes written ... >>
<< Java program to get the last modification date and...