Java append file


 

Java append file

In this section, you will learn how to append the text to the file.

In this section, you will learn how to append the text to the file.

Java append file

In this section, you will learn how to append the text to the file.

This has become a common task. You can easily append any text to the existing file by using either FileOutputStream or by FileWriter class. The data will always added to the end of the file and will not change the pre-exist data. If you are using FileOutputStream, then you have to specify two parameters:
name- file name
append- if true, then bytes will be written to the end of the file.

The following code create the output file stream to write the specified string to the end of the file.

 FileOutputStream out=new FileOutputStream("C:/new.txt", true);

getBytes() method- This is the method of String which converts the string into byte array.

write()- This is the method of FileOutputStream which writes the byte array to the file output stream.

close()- This is the method of FileOutputStream which closes the output stream.

Here is the code:

import java.io.*;

class AppendFile {
  public static void main(String[] args) {
    try {
      FileOutputStream out = new FileOutputStream(new File("C:/new.txt"),
          true);
      String str = "There is always a way-if you're committed.";
      out.write(str.getBytes());
      out.close();
      System.out.println("String is appended.");
    catch (IOException e) {
    }
  }
}

There is another way of appending the text by using FileWriter and BufferedWriter classes. Here you have to invoke the FileWriter constructor in the proper manner. The class FileWriter too have two parameters, name and append:
name- file name
append- if true, then bytes will be written to the end of the file.

FileWriter: This class is used to write stream of characters. In the constructor of this class if you put append value to true with the file name then the specified data will get added to the file without overwritten the existing data.

BufferedWriter: This class provide efficient writing of single characters, arrays, and strings.

write() method-This method writes the string.

newLine() method- This method of BufferedWriter class allow to write the text in next line.

Here is the code:

import java.io.*;

class AppendFile {
  public static void main(String[] args) {
    try {
      BufferedWriter out = new BufferedWriter(new FileWriter(
          "C:/new.txt"true));
      out.write("There is always a way-if you're committed.");
      out.newLine();
      out.close();
      System.out.println("String is appended.");
    catch (IOException e) {
    }
  }
}

Through the above code, you can append data to the text file without overwritten pre-exist data.

Ads