charcount.java

来自「程序练习中包括书中实例程序代码和练习中要用到的代码,是压缩文件」· Java 代码 · 共 43 行

JAVA
43
字号
package examples.exceptions;

import java.io.*;

/** A class to help demonstrate how the finally
  * clause can be used with a try block
  */
public class CharCount {
   /** Method to count characters in a file
     * @param args[0] The name of the file to be
     *                opened for character counting
     */
   public static void main( String[] args ) {
      if ( args.length == 0 ) {
         System.err.println( "Please provide "
                             + "a file name." );
      } else try {
         FileReader input
            = new FileReader( args[0] );
   
         int charCount = 0;
         try {
            while ( input.read() != -1 ) {
               charCount++;
            }
            System.out.println( "There were "
                                + charCount
                                + " characters" );
         } catch( IOException iox ) {
            System.err.println( "Exception occurred "
                                + "at character "
                                + charCount );
            System.err.println( iox );
         } finally {
            input.close();
         }
      } catch( IOException iox ) {
         System.err.println( "Error opening or "
                             + "closing the file "
                             + args[0] );
      }
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?