
import java.io.*;

/**
 * A demonstration of how to read text from a file and use random numbers.
 */
public class Files {

    /**
     * Read a few lines from each of the files named on the command line,
     * and pick one line from each.
     */
    public static void main(String args[]) {
        if (args.length == 0) {
            System.out.println("usage: java File <file> ...\n"
                    + "  prints a randomly selected line from the top\n"
                    +"   of each of the files named on the command line.");
            return;
        }
        for (int i = 0; i < args.length; i++) {
            String filename = args[i];
            System.out.println("Picking random line from top of "+
                    filename+" ...");
            pickLineFromFile(filename);
        }
    }

    /**
     * Print a random line from the top of the named file.
     */
    static void pickLineFromFile(String filename) {
        BufferedReader in;

        try {
            in = new BufferedReader(new FileReader(filename));
        } catch (FileNotFoundException e) {
            System.err.println(e);
            return;
        }

        int n_lines = 5;
        String lines[] = new String[n_lines];
        for (int i = 0; i < n_lines; i++) {
            try {
                lines[i] = in.readLine();
            } catch (IOException e) {
                lines[i] = null; // same as EOF indicator
            }
            if (lines[i] == null) { // end-of-file
                n_lines = i;
                break;
            }
        }
        if (n_lines == 0) {
            System.err.println("File is empty");
            return;
        }
        String line = lines[(int)(Math.random() * n_lines)];
        System.out.println(line);
    }

}

