Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

Question about strange NullPointerException



This is my code about roughly counting character counts by adding lengths of the each file names given by command line arguments... Strangely, it generates NullPointerException on line 50(ch += in.readLine().length();) if implemented without the println method above it; but if I implement the println, and then run it, the method commences with no problem. I wonder why this is happening. Can somebody help?

Code is like this...

package chapter2;
import java.io.*;
public class exer13
{
public static void main(String[] args)
{
if(args.length==0)
System.out.println("Error: provide command line arguments");
for(String fileName: args){
processFile(fileName);
}


}
public static void processFile(String fileName){
FileReader theFile;
        BufferedReader fileIn = null;

        System.out.println( "FILE: " + fileName );
        try
        {
            theFile = new FileReader( "C:/Users/ybjoony/workspace/book/src/chapter2/"+fileName );
            fileIn  = new BufferedReader( theFile );
            System.out.println("Number Of Characters: " + countChar(fileIn));
        }
        catch( IOException e )
          {  System.out.println( e ); }
        finally
        {
            // Close the stream
            try
            {
                if(fileIn != null )
                    fileIn.close( );
            }
            catch( IOException e )
              { }
}

}
//Somehow fails if implemented w/o println statements. catch statements doesn't seem to work.
public static int countChar(BufferedReader in)
{
int ch = 0;
if(in==null) throw new NullPointerException();

try{
System.out.println(in.readLine());
while(in.readLine()!=null){
ch += in.readLine().length();
}
}catch(IOException e){System.out.println(e);}
//catch(NullPointerException e){System.out.println(e);}
return ch;
}
}