scg/ch10/EchoFile

From FANG

Jump to: navigation, search

01 package scg.ch10;
02 
03 import java.io.File;
04 import java.io.FileNotFoundException;
05 import java.util.Scanner;
06 
07 /**
08  * A program which reads its command-line arguments, treating each as
09  * the name of a file. An EchoFile object reads its file one line at a
10  * time and echos them to standard output.
11  */
12 public class EchoFile {
13   /**
14    * internal representation of a file on disk; represents the file
15    * entity, not the contents
16    */
17   private final File file;
18 
19   /**
20    * Construct a new {@link EchoFile} object with the given file name.
21    *
22    @param  fname  full path to the file to echo
23    */
24   public EchoFile(String fname{
25     file = new File(fname);
26   }
27 
28   /**
29    * The arguments are assumed to be the names of files. Each is opened
30    * and echoed to the screen.
31    *
32    @param  args
33    */
34   public static void main(String[] args{
35     for (int argNdx = 0; argNdx != args.length; ++argNdx{
36       EchoFile nextFile = new EchoFile(args[argNdx]);
37       nextFile.echo();
38     }
39   }
40 
41   /**
42    * Echo the file to standard output. If there is a problem with the
43    * file not existing or not being readable by the current user, an
44    * appropriate error message should be printed.
45    */
46   public void echo() {
47     if (file.exists() && file.canRead()) {
48       try {
49         Scanner echoScanner = new Scanner(file);
50         String line;
51         while (echoScanner.hasNextLine()) {
52           line = echoScanner.nextLine();
53           System.out.println(line);
54         }
55         echoScanner.close();
56       } catch (FileNotFoundException e{
57         System.out.println("PANIC: This should never happen!");
58         e.printStackTrace();
59       }
60     } else {
61       System.out.println("Unable to open \"" + file.getName() +
62         "\" for input");
63     }
64   }
65 }
66 
67 //Uploaded on Mon Mar 29 21:41:01 EDT 2010


Download/View scg/ch10/EchoFile.java





Views
Personal tools
Add to 
del.icio.usAdd to 
diggAdd to 
FacebookAdd to 
favoritesAdd to 
GoogleAdd to 
MySpaceAdd to 
PrintAdd to 
SlashdotAdd to 
StumbleUponAdd to 
Twitter

Games
Games