Simple logger class but is throwing a null pointer exception?

前端 未结 2 857
渐次进展
渐次进展 2021-01-15 12:45

I have written a simple logger class that I can make an instance of and it will allow me to write information to a file. It was working in one example a while back but now i

相关标签:
2条回答
  • 2021-01-15 13:22

    You are "shadowing" the pw variable inside of your openPrintWriterStream() method by providing a parameter with the same name - pw - as a field in the class. See http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html, the "Parameter Names" section:

    A parameter can have the same name as one of the class's fields. If this is the case, the parameter is said to shadow the field. Shadowing fields can make your code difficult to read and is conventionally used only within constructors and methods that set a particular field.

    There are several approaches to fix this:

    1. As matt forsythe suggests, quit passing the PrintWriter as an argument to openPrintWriterStream(), and then lazily construct it only if it is null.

    2. Initialize the PrintWriter in the DDHLogger(String filePath, String yourfilename) constructor, since you have all the information you need there to construct the PrintWriter, like the code sample below.

    The second approach allows you to clean up your code somewhat by removing all the calls to openPrintWriterStream(pw).

    public DDHLogger(String filePath, String yourfilename) 
    {
        System.out.println("filePath: " + filePath);
        System.out.println("yourfilename: " + yourfilename);
         //String fileName = "C:\\Users\\home-1\\Desktop\\" + yourfilename;
         String fileName = filePath + yourfilename;
         System.out.println("fileName::--> " + fileName);
        // file = new File(fileName);//Creates the file
         file = new File(fileName);//Creates the file
         System.out.println("file: " + file);
         try {
            fw = new FileWriter(file, true);
            //INSTANTIATE PRINTWRITER HERE
            pw = new PrintWriter(fw);
        } catch (IOException e) {
            e.printStackTrace();
        }//allows append to the file without over writing. The TRUE keyword is used for append
    
    }
    

    Finally, remove the DDHLogger() or make it it private, since classes in the same package can still use it to create DDHLoggers without the required File and FileWriter, potentially causing NullPointerExceptions in the future.

    0 讨论(0)
  • 2021-01-15 13:23

    Your openPrintWriterStream does not actually affect the member variable named pw. Also, since you reassign the pw reference at the very beginning of the method (and don't return the updated reference) the assignment is basically ineffective. Get rid of the pw argument, so that the assignment actually updates the member variable. You will need to put in a check to ensure that pw has not already been opened.

    0 讨论(0)
提交回复
热议问题