Share this page 

Write to the end of a fileTag(s): IO


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class AppendToFile {
   public static void main(String[] args) throws IOException {
      Path path = Paths.get("c:/temp/output.txt");

      if (Files.exists(path)) {
         Files.write(Paths.get("c:/temp/output.txt"),
               "Hello World\n".getBytes(),
               StandardOpenOption.APPEND);
      }
      else {
         Files.write(Paths.get("c:/temp/output.txt"),
               "Hello World\n".getBytes(),
               StandardOpenOption.CREATE_NEW);
      }
   }
}

[JDK1.1]

import java.io.FileOutputStream;
import java.io.IOException;

public class AppendToFile {

   public static void main(String[] args) throws IOException {
      FileOutputStream fos = null;
      try {
         // open in append mode if it exists, if not create a new file
         fos = new FileOutputStream("c:/temp/output.txt", true);
         fos.write("Hello World\n".getBytes());
      }
      finally {
         if (fos !=null) {
            fos.close();
         }
      }
   }
}

[JDK1.0.2]

import java.io.*;
public class appendtext {
  public static void main(String args[]){
  try {
    PrintStream out =
        new PrintStream(new AppendFileStream("myfile"));
    out.print("A new line of text");
    out.close();
    }
   catch(Exception e) {
    System.out.println(e.toString());
    }
   }
}

class AppendFileStream extends OutputStream {
   RandomAccessFile fd;
   public AppendFileStream(String file) throws IOException {
     fd = new RandomAccessFile(file,"rw");
     fd.seek(fd.length());
     }
   public void close() throws IOException {
     fd.close();
     }
   public void write(byte[] b) throws IOException {
     fd.write(b);
     }
   public void write(byte[] b,int off,int len) throws IOException {
     fd.write(b,off,len);
     }
   public void write(int b) throws IOException {
     fd.write(b);
     }
}