简体   繁体   中英

,Exception in thread "main" java.lang.NullPointerException

I am trying to write a code to remove comment line from the input java file. I am getting this error:

Exception in thread "main" java.lang.NullPointerException

It is showing error in return new String(buffer) , and the word "String" everywhere in the program.

package javaapplication3;  
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class JavaApplication3 {

    public static void main(String[] args) {
        String source = readFile("sorce.java");    
        System.out.println(source.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|    (?://.*)",""));    
    }

    static String readFile(String fileName) {    
        File file = new File(fileName);    
        char[] buffer = null;    
        try {    
            BufferedReader bufferedReader = new BufferedReader(
                new FileReader(file));    
            buffer = new char[(int)file.length()];    
            int i = 0;    
            int c = bufferedReader.read();
            while (c != -1) {
                buffer[i++] = (char)c;
                c = bufferedReader.read();    
            }
        } catch (IOException e) {    
            e.printStackTrace();  
        }  
        return new String(buffer);
    }
}

You initialized buffer to null , and it must still be null at

return new String(buffer);

Therefore, this line in the try block never ran:

buffer = new char[(int)file.length()];

There must have been an IOException thrown in the line above it, but you caught it and ignored it. That is probably the worst thing you can do when catching an exception.

Properly handle the IOException by at least printing a stack trace. Then you can fix the cause of that exception and get your code to work.

But if there is an IOException , then you must handle that case properly with regards to avoiding the NullPointerException , possibly by letting the caller of the method handle the IOException .

You must never initialized a variable with "null" if you don't want that this variable was null.

Try, char buffer [ ]= new char[ ];

Advice: put always in your method main:

public static void main(String[ ] args)throws IOException{

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM