scg/ch14/core/CountCharacters

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 
08 /**
09  * A program which reads its command-line arguments, treating each as
10  * the name of a file. A {@link CountCharacters} object reads its file
11  * one character at a time using a {@link FileReader}.
12  */
13 public class CountCharacters {
14   /** named constant for the end of file return value */
15   public static final int EOF = -1;
16 
17   /**
18    * The arguments are assumed to be the names of files. Each is opened
19    * and echoed to the screen.
20    *
21    @param  args  names of the files to echo
22    */
23   public static void main(String[] args{
24     for (int argNdx = 0; argNdx != args.length; ++argNdx{
25       CountCharacters nextFile = new CountCharacters(args[argNdx]);
26       nextFile.count();
27     }
28   }
29 
30   /** the file to open */
31   private final File file;
32 
33   /**
34    * Construct a new {@link CountCharacters} object for the named file.
35    *
36    @param  fname  the full path name of the file
37    */
38   public CountCharacters(String fname{
39     file = new File(fname);
40   }
41 
42   /**
43    * If possible read the file, character-by-character, counting the
44    * characters.
45    */
46   public void count() {
47     if (file.exists() && file.canRead()) {
48       FileReader reader = null;
49       try {
50         reader = new FileReader(file);
51         int characterCount = 0;
52 
53         int ch = reader.read();
54         while (ch != EOF{
55           ++characterCount;
56           ch = reader.read();
57         }
58         System.out.println(file.getName() + ": " + characterCount);
59       } catch (FileNotFoundException e{
60         System.err.println("PANIC: This should never happen!");
61         e.printStackTrace();
62       } catch (IOException e{// file was opened before this exception
63         System.err.println("Problem while reading \"" + file.getName() +
64           "\".");
65         e.printStackTrace();
66       } finally {
67         try {
68           if (reader != null{
69             reader.close();
70           }
71         } catch (IOException e1{
72           System.err.println(
73             "Error closing Reader assciated with + \"" +
74             file.getName() + "\".");
75           e1.printStackTrace();
76         }
77       }
78     } else {
79       System.err.println("Unable to open \"" + file.getName() +
80         "\" for input");
81     }
82   }
83 }
84 
85 //Uploaded on Mon Mar 29 21:40:01 EDT 2010


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