Example of Output to Files

You create a new FileOutputStream object by passing the name of the file to the constructor, like this:

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

If a file with this name already exists in the current working directory, it will be overwritten by the new data. If the file doesn't exist it will be created in the current directory.

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

import java.io.*;


public class MultiType {

  public final static int BUFFER_SIZE = 4096;

  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]); 
      }
      catch (IOException ex) {
        System.err.println(e); 
      }
    } // end for
    
    try {
      byte[] buffer = new byte[BUFFER_SIZE];
      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.getMessage()); 
            }
        } // end for
      } // end while
    } // end try
    catch (IOException ex) {
      System.err.println(e); 
    }

  } // end main
  
}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2003 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 22, 2003