<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">// iodemo
import java.io.*;
import javax.swing.*;
public class IO {
    
    // either null or the last directory that a JFileChooser looked at
    // (in function getFile, not function getFile1)
    private static File lastDirectory= null;
    
    /** = a file name from user using JFileChooser */
    public static File getFile1() throws IOException {
        JFileChooser jd= new JFileChooser();
        jd.setDialogTitle("Choose input file");
        jd.showOpenDialog(null);
        return jd.getSelectedFile();
    }
    
    /** = a file name from user using JFileChooser using the last directory looked at.
          Makes use of private static variable lastDirectory */
    public static File getFile()  {
        JFileChooser jd;
        
        if (lastDirectory==null)
             { jd= new JFileChooser();}
        else { jd= new JFileChooser(lastDirectory); }
        
        jd.setDialogTitle("Choose input file");
        jd.showOpenDialog(null);
        
        if (jd.getSelectedFile()==null)
            return null;
        lastDirectory= jd.getSelectedFile().getParentFile();
        return jd.getSelectedFile();
    }
    
    /** Obtain a file name from the user using JFileChooser and return a
        reader that is linked to it. A FileReader has a function read() that
        reads the next character and yields its integer representation */
    public static FileReader getFileReader() throws IOException {
        File file= getFile();
        if (file==null)
            return null;
        
        return new FileReader(file);
    }
    
    /** Obtain a file name from the user using JFileChooser and return a reader
        that is linked to it. A Bufferedreader has a method readLine() that
        reads the next line and yields it as a String */
    public static BufferedReader getReader() throws IOException {
        File file= getFile();
        if (file==null)
            return null;
        
        FileReader fr= new FileReader(file);
        return new BufferedReader(fr);
        
    }
    
    // Get a file from the user and print the lines of the file
    public static void pL() throws IOException {
        BufferedReader bf= getReader() ;
        if (bf==null)
            return;
        
        String line= bf.readLine();
        // invariant: the lengths of lines before line line have been printed and
        // line is the next one to print and the rest haven't been read yet
        while (line != null) {
            System.out.println(line);
            line= bf.readLine();
        }
    }
}

</pre></body></html>