import java.io.*;
import java.util.*;
import javax.swing.*;

/** Class to demo reading of files
 */
public class LabReadingFiles {
    
    /** = the number of lines in a file chosen by the caller */
    public static int lines() throws IOException {
        BufferedReader bf= getReader(null);
        String lin= bf.readLine();
        int n= 0;
        // invariant: n is the number of lines that precede line lin, and
        //            lin is the next line to process (null if no more).
        while (lin != null) {
            // Process line lin
            n= n + 1;
            
            lin= bf.readLine();
        }
        
        return n;
    }
    
    
    
    
    /** Obtain a file name from the user using a JFileChooser)
        and return a reader that is linked to it. If p is not null
        (it can be), start the JFileChooser at the path given by p*/
    public static BufferedReader getReader(String p) {
        try {
            JFileChooser jd;
        if (p == null) {
            jd= new JFileChooser();
        }
        else {
            jd= new JFileChooser(p);
        }
        jd.setDialogTitle("Choose input file");
        jd.showOpenDialog(null);
        
        FileReader fr= new FileReader(jd.getSelectedFile());
        return new BufferedReader(fr);
        }
        catch (IOException e) {
            return null;
        }
    }
}
