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 the file exists in the current 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 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 e) {
        System.err.println(e); 
      }
    } // end for
    
    try {
       while (true) {
        int n = System.in.available();
        if (n > 0) {
          byte[] b = new byte[n];
          int result = System.in.read(b);
          if (result == -1) break;
          for (int i = 0; i < args.length; i++) {
            try {
              fos[i].write(b, 0, result); 
            }
            catch (IOException e) {
              System.err.println(e); 
            }
          } // end for
        } // end if   
      } // end while
    } // end try
    catch (IOException e) {
      System.err.println(e); 
    }

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


  } // end main
  
}

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