scg/ch14/core/EchoFileWithFilterReader

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


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