import java.io.*;
import java.awt.*;

/**
 * Simple class to write lines to a text file. To use, create a
 * <code>LineWriter</code> object, then send it the
 * <code>writeLine(line)</code> message as many times as desired.
 * When you are finished writing, you should <code>close()</code>
 * the file. Failure to close the file will probably result in
 * loss of data.
 *
 * @author: David Matuszek
 * @version 2.0
 */
 
public class LineWriter{
    PrintWriter printWriter = null;
    
    /**
     * Presents an open file dialog and opens the chosen file for writing.
     * 
     * @param message The message to display in the title bar of the dialog box.
     */
    LineWriter(String message){
        // use a file dialog to get the name and directory of a file
        FileDialog dialog = new FileDialog(new Frame(), message, FileDialog.LOAD);
        dialog.setVisible(true);
        String dir = dialog.getDirectory();
        String file = dialog.getFile();

        // make sure we got a file
        if (dir == null || file == null){
            System.err.println ("No file selected.");
            return;
        }
    
        // construct the full path name of the file
        String fileName = dir + file;
        
        // create and remember a writer for the file
        try {printWriter = new PrintWriter(new FileOutputStream(fileName), true);}
        catch(Exception e) {
            System.err.println("LineWriter can't " + "use output file: " + fileName);
        }
    }

    /**
     * This constructor is used if you forget to supply a message to
     * be displayed in the dialog box.
     */
    LineWriter() {
        this("Write lines to what file?");
    }
    
    /**
     * Writes a line to this file.
     * 
     * @param line The line to be written.
     */
    void writeLine(String line) {
        printWriter.println(line);
    }
    
    /**
     * Closes the file.
     */
    void close() {
        printWriter.flush();
        try{printWriter.close();}
        catch(Exception e){}
    }
}