UCL Logo

Class FileOutput

Writing data to a file

Writing data to a file requires the following steps:

1. Decide what type of data you want to write to the file and in which order to write it. A file can contain different types of data but to read it back into a program you need to know what the types are, the order in which the data appears and the amount of data of each type.

2. Determine the file name of the file to be written.

3. Try to open the file for writing. This will connect your program to the file. Opening a file can fail (if, for instance, the file name is invalid).

4. Write the data to the file. Often this is done in a loop, to write a whole sequence of data. Writing to a file can also fail unexpectedly (for example, there may be no disk space left).

5. Close the file. This must be done to ensure that all the data you have written to the file actually gets stored in the file (data you write is typically buffered somewhere so that data is written to a file in larger lumps - this is more efficient). If a file is not closed properly you may find that data is missing from the end of the file next time you try to read it.

The following program shows how data can be written to a file using the FileOutput class listed at the end of these notes.

class FileOutputTest
{
  public static void main(String[] args)
  {
    // Create and open file. 
    FileOutput out = new FileOutput("outputtest1.dat") ;
 
    // Write different types of value.
    // Each line must be explicitly separated
    // with a newline.   
    out.writeInteger(100) ;
    out.writeNewline() ;
    out.writeLong(1234567L) ;
    out.writeNewline() ;
    out.writeDouble(1.23456D) ;
    out.writeNewline() ;
    out.writeFloat(2.34567F) ;
    out.writeNewline() ;
    out.writeCharacter('a') ;
    out.writeNewline() ;
    // With a String, the newline character can be included
    // in the String value.
    out.writeString("Hello world\n") ;
    // Must close the file when finished otherwise
    // data can be lost.
    out.close() ;
  }
}

Data is stored in a file as normal, readable characters. For example, the integer 12345 is stored as the text 12345, even though it is stored in binary format within a program. Any data file can be loaded into emacs for viewing and editing. Typically each item of data (an integer, floating point number, text string, etc.) is stored on a separate line, as the newline is used as a marked to indicate the end of the data item.


The following class, called FileOutput, provides a number of methods to write data to a text file. Copy this class to a file called FileOutput.java and compile it. Then include a copy of the .class file in any directory where you are writing a program that needs to write to a file. This class can be used in a program at the same time as class FileInput, so you can write programs that do both file input and output. Also, like FileInput, the FileOutput class is a toy class, and would not be used in a real, robust application program.

A file can be opened for output using a statement like:

FileOutput myFile = new FileOutput("aFileName") ;

The file name can either be given directly as a quoted string or as a String variable.

When a file is opened for writing, it will either create a new file if there is no existing file with the same name or reuse an existing file. However, if an existing file is reused any data in the file will be overwritten and destroyed. Beware!

If you want to append output to the end of an existing file, without overwriting the data it already contains, then you need to set the append mode. This is easily done by providing an extra parameter when the FileOutput is object is created:

   FileOutput out = new FileOutput("outputtest1.dat",true) ;

Here the file name is followed by a second parameter, the boolean true. Any output written to the file will now be added without the existing content being overwritten. (Setting the boolean parameter to false turns off append mode, giving the default behaviour.)

The FileOutput methods are:

  • writeInt(int) - write an integer
  • writeLond(long) write a long
  • writeDouble(double) - write a double
  • writeFloat(float) - write a float
  • writeCharacter(char) - write a single character
  • writeString(String) - write a String
  • writeNewline - write a newline character (the format of the newline will depend on what kind of machine you run the program on.

If an error occurs when writing data, then the program will be automatically terminated after displaying an error message.

import java.io.*;
/**
 *  A simple output class to write values to a file of characters. If any file
 *  errors occur, methods in this class will display an error message and
 *  terminate the program.
 *
 *@author     Graham Roberts
 *@version    1.2
 */

public class FileOutput
{
  /**
   *  Instance variables to store file details.
   */
  private String filename = "";
  private BufferedWriter writer = null;


  /**
   *  Construct FileOutput object given a file name.
   *
   *@param  fname  Description of the Parameter
   */
  public FileOutput(String fname)
  {
    this(fname, false);
  }


  /**
   *  Construct FileOutput object given a file name and append mode. If append
   *  is true then data will be appended to the end of an existing file.
   *
   *@param  fname   Description of the Parameter
   *@param  append  Description of the Parameter
   */
  public FileOutput(String fname, boolean append)
  {
    filename = fname;
    try
    {
      writer = new BufferedWriter(new FileWriter(filename, append));
    }
    catch (IOException e)
    {
      error("Can't open file: " + filename);
    }
  }


  /**
   *  Close the file when finished
   */
  public void close()
  {
    try
    {
      writer.close();
    }
    catch (IOException e)
    {
      error("Can't close file: " + filename);
    }
  }


  /**
   *  Write an int value to a file.
   *
   *@param  i  Description of the Parameter
   */
  public final synchronized void writeInteger(int i)
  {
    try
    {
      writer.write(Integer.toString(i));
    }
    catch (IOException e)
    {
      error("writeInteger failed for file: " + filename);
    }
  }


  /**
   *  Write a long value to a file.
   *
   *@param  l  Description of the Parameter
   */
  public final synchronized void writeLong(long l)
  {
    try
    {
      writer.write(Long.toString(l));
    }
    catch (IOException e)
    {
      error("writeLong failed for file: " + filename);
    }
  }


  /**
   *  Write a double value to a file.
   *
   *@param  d  Description of the Parameter
   */
  public final synchronized void writeDouble(double d)
  {
    try
    {
      writer.write(Double.toString(d));
    }
    catch (IOException e)
    {
      error("writeDouble failed for file: " + filename);
    }
  }


  /**
   *  Write a float value to a file.
   *
   *@param  f  Description of the Parameter
   */
  public final synchronized void writeFloat(float f)
  {
    try
    {
      writer.write(Float.toString(f));
    }
    catch (IOException e)
    {
      error("writeFloat failed for file: " + filename);
    }
  }


  /**
   *  Write a char value to a file.
   *
   *@param  c  Description of the Parameter
   */
  public final synchronized void writeCharacter(char c)
  {
    try
    {
      writer.write(c);
    }
    catch (IOException e)
    {
      error("writeCharacter failed for file: " + filename);
    }
  }


  /**
   *  Write a String value to a file.
   *
   *@param  s  Description of the Parameter
   */
  public final synchronized void writeString(String s)
  {
    try
    {
      writer.write(s);
    }
    catch (IOException e)
    {
      error("writeString failed for file: " + filename);
    }
  }


  /**
   *  Write a newline to a file.
   */
  public final synchronized void writeNewline()
  {
    try
    {
      writer.write("\n");
    }
    catch (IOException e)
    {
      error("writeNewline failed for file: " + filename);
    }
  }


  /**
   *  Deal with a file error
   *
   *@param  msg  Description of the Parameter
   */
  private void error(String msg)
  {
    System.out.println(msg);
    System.out.println("Unable to continue executing program.");
    System.exit(0);
  }

}


Last updated: August 30, 2006

Computer Science Department - University College London - Gower Street - London - WC1E 6BT - Telephone: +44 (0)20 7679 7214 - Copyright 1999-2006 UCL


 Search by Google