Main site links: Home | Moodle | Theory pages | Java pages

Code:SimpleReader

From CompWiki

Jump to: navigation, search

Simple Reader

To read in files we use the SimpleReader Class

import java.awt.*;
import java.io.*;
/**
* Class to read and from a simple text file
*
* @author Mr J
* @version 1.0
*/
public class SimpleReader
{
  private BufferedReader inFile;

  public SimpleReader(String fileName) throws IOException
  {
    inFile = new BufferedReader(new FileReader(fileName));
  }
  public String readLine() throws IOException
  {
    return inFile.readLine();
  }
}

The code to use this SimpleReader might look like this:

/**
* load some array contents from text file
*/
private void readFromFile()
{
  try
  {
    SimpleReader reader = new SimpleReader(FILENAME);
    // read first line of file, if file is empty should be EOF
    String next = reader.readLine();
    while (next != null)
    {
      // process this line - eg add to an array
      next = reader.readLine();
    } 
  }
  catch(IOException io)
  {
    messages.setText("Error reading from file");
  }
}

Further ideas reading from text files:

  • Use a text file to store setup or start up options for an application. Eg an application might want to store the location of data files in a text file. It could store usernames and passwords although this is not very secure.
  • Use a text file to store different language options for menus and error messages. So the English version loads all the Strings into an array and outputs them using an array index. Another file holds all the translations into another language - the user chooses their language and your program simply reads the different file.
  • Use text files to hold data for a simulation, eg a supermarket queueing simulation. The file holds data like the number of checkouts, the number of customers, their average shopping cart load etc. The simulation can easily be run with different data sets. You could write results of the simulation into a text file.
  • Expand the SimpleReader to read special types of file, such as csv (comma separated variable) files into your program. Such files can be output by most office packages (eg Word and Excel). For example, if you were writing a gradebook application, class lists might already be available in Excel. You might write a readObject() method after defining a suitable Class.

One advantage of using a text file is that all computer users pretty much know how to edit them using Notepad - but this could also be a disadvantage of course if they screw up your structure.

Personal tools
TOOLBOX
LANGUAGES