Appending data to files

It's often useful to be able to append data to an existing file rather than overwriting it. To do this just pass the boolean value true as the second argument to the FileOutputStream() constructor. For example,

FileOutputStream fos = new FileOutputStream("16.html", true);

The following example reads user input from System.in and appends it to the files specified on the command line.

import java.io.*;


public class Append {

  public static final int BUFFER_SIZE = 1024;

  public static void main(String[] args) {

    FileOutputStream[] fos = new FileOutputStream[args.length];

    for (int i = 0; i < args.length; i++) {
      try {
        fos[i] = new FileOutputStream(args[i], true); 
      }
      catch (IOException ex) {
        System.err.println(e); 
      }
    } // end for
    
    byte[] buffer = new byte[BUFFER_SIZE];
    try {
      while (true) {
        int result = System.in.read(buffer);
        if (result == -1) break;
        for (int i = 0; i < args.length; i++) {
          try {
            fos[i].write(buffer, 0, result); 
          }
          catch (IOException ex) {
            System.err.println(ex); 
          }
        } // end for
      } // end while
    } // end try
    catch (IOException ex) {
      System.err.println(ex); 
    }

    for (int i = 0; i < args.length; i++) {
      try {
        fos[i].close(); 
      }
      catch (IOException ex) {
        System.err.println(ex); 
      }
    } // end for


  } // end main
  
}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified July 8, 1998