A simple example of java appending content to the end of a file

  • 2020-05-19 04:56:41
  • OfStack

As follows:


import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 *  Appends the content to the end of the file .
 * @author haicheng.cao
 *
 */
public class AppendToFile {
  /**
   * A Method append file: use RandomAccessFile
   */
  public static void appendMethodA(String fileName, String content) {
    try {
      //  Open the 1 Random access to the file stream, by read and write 
      RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
      //  File length, number of bytes 
      long fileLength = randomFile.length();
      // Moves the write file pointer to the end of the file. 
      randomFile.seek(fileLength);
      randomFile.writeBytes(content);
      randomFile.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * B Method append file: use FileWriter
   */
  public static void appendMethodB(String fileName, String content) {
    try {
      // Open the 1 File writer, the first in the constructor 2 A parameter true Means to write a file as an append 
      FileWriter writer = new FileWriter(fileName, true);
      writer.write(content);
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    String fileName = "C:/temp/newTemp.txt";
    String content = "new append!";
    // According to the method A Additional documents 
    AppendToFile.appendMethodA(fileName, content);
    AppendToFile.appendMethodA(fileName, "append end. \n");
    // Display file contents 
    ReadFromFile.readFileByLines(fileName);
    // According to the method B Additional documents 
    AppendToFile.appendMethodB(fileName, content);
    AppendToFile.appendMethodB(fileName, "append end. \n");
    // Display file contents 
    ReadFromFile.readFileByLines(fileName);
  }
}

Related articles: