/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * Head.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 3-1: * Write a program named Head that prints out the first ten lines of each file * specified on the command line. * * @author Matthew Feldt * @version 1.0, 01/30/2001 8:39 */ package com.feldt.examples.io; import java.io.*; public class Head { public static void main (String args[]) { final int NUM_LINES = 10; final String usage = "Usage: java Head file ..."; BufferedReader in; String out; if (args.length < 1) fail(usage); // print the first NUM_LINES from files supplied on the command line for (int i = 0; i < args.length; i++) { try { File f = new File(args[i]); if (! f.exists()) fail(args[i] + ": no such file or directory."); if (! f.canRead()) fail(args[i] + ": read protected."); if (! f.isFile()) fail(args[i] + ": is not a regular file."); in = new BufferedReader(new FileReader(f)); // print the filename System.out.println("::::::::::::::"); System.out.println(f); System.out.println("::::::::::::::"); // print up to NUM_LINES from the beginning of the file for (int j = 0; j < NUM_LINES; j++) { out = in.readLine(); if (out == null) break; else System.out.println(out); } } catch(IOException e) { System.err.println(e.getMessage()); } catch(IllegalArgumentException e) { System.err.println(e.getMessage()); } } } /** shorthand method to throw an exception with the appropriate message */ protected static void fail(String msg) throws IllegalArgumentException { throw new IllegalArgumentException(msg); } }