scg/ch14/core/EchoFileWithReader

From FANG

Jump to: navigation, search

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


Download/View scg/ch14/core/EchoFileWithReader.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