Doug Hauf
Doug Hauf

Reputation: 3213

Simple logger class but is throwing a null pointer exception?

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 is throwing a NULL pointer exception error. I really do not know why this would be the case. I have placed the class code below.

Class Code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Date;

/*This class is a simple logger that currently only has one message but will be added to it in time*/
public class DDHLogger  {
    Date timeStamp = new Date();
    PrintWriter pw = null;
    FileWriter fw;
    File file;

    //FileOutputStream   fstre;  
    //OutputStreamWriter outFileStream;


    /**
     * Used for creating the file when the object is implemented.
     * @param yourstring
     * @param yourfilename
     * @throws IOException -- file check
     */
    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);
        } catch (IOException e) {
            e.printStackTrace();
        }//allows append to the file without over writing. The TRUE keyword is used for append
    }

    /**
     * Must supply two parmaters. The first parmater is the string that is to be written to the file. The second parmater is used for
     * the file name. The extension C: for the default path.
     * @param yourstring
     * @param yourfilename
     */
    void Error(String yourstring, String lineNumber){
        openPrintWriterStream(pw);
        try{
            pw.println("ERROR: " + yourstring + " * " + timeStamp.toString() +" * " + " Line Number: " + lineNumber + "\n");
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }  
    }

    void Debug(String yourstring, String lineNumber){
         openPrintWriterStream(pw);
         try{
             pw.println("DEBUG: " + yourstring + " ******* " + timeStamp.toString() +" ******* " + " Line Number: " + lineNumber + "\n");
             pw.close();
         } catch (Exception e) {
             e.printStackTrace();
         }   
   }

   void Info(String yourstring, String lineNumber) {
       openPrintWriterStream(pw);
       try{
           pw.println("INFORMATION: " + yourstring + " ******* " + timeStamp.toString() +" ******* " + " Line Number: " + lineNumber + "\n");
           pw.close();
       } catch (Exception e) {
           e.printStackTrace();
       } 
   }

   void Warn(String yourstring, String lineNumber){
       openPrintWriterStream(pw);
       try{
           pw.println("Warning: " + yourstring + " ******* " + timeStamp.toString() +" ******* " + " Line Number: " + lineNumber + "\n");
           pw.close();
       } catch (Exception e) {
           e.printStackTrace();
       }    
  }

   void openPrintWriterStream(PrintWriter pw) {
       pw = new PrintWriter(fw);
         try {
            fw = new FileWriter(file, true);
        } catch (IOException e) {
            e.printStackTrace();
        } 
   }
}

Null pointer exception:

filePath: C:\Users\home-1\Desktop\
yourfilename: PokerLogger.txt
fileName::--> C:\Users\home-1\Desktop\PokerLogger.txt
file: C:\Users\home-1\Desktop\PokerLogger.txt
java.lang.NullPointerException
    at DDHPokerGame.DDHLogger.Info(DDHLogger.java:76)
    at DDHPokerGame.DDHGamePanel$1.mouseEntered(DDHGamePanel.java:150)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.trackMouseEnterExit(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
java.lang.NullPointerException
    at DDHPokerGame.DDHLogger.Info(DDHLogger.java:76)
    at DDHPokerGame.DDHGamePanel$1.mouseExited(DDHGamePanel.java:155)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.trackMouseEnterExit(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
java.lang.NullPointerException
    at DDHPokerGame.DDHLogger.Info(DDHLogger.java:76)
    at DDHPokerGame.DDHGamePanel$1.mouseEntered(DDHGamePanel.java:150)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.trackMouseEnterExit(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
java.lang.NullPointerException
    at DDHPokerGame.DDHLogger.Info(DDHLogger.java:76)
    at DDHPokerGame.DDHGamePanel$1.mouseExited(DDHGamePanel.java:155)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.trackMouseEnterExit(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

New and cleaned up Code:

/*This class is a simple logger that currently only has one message but will be added 
  to it in time*/

public class DDHLogger  {
    Date timeStamp = new Date();
    PrintWriter pw = null;
    FileWriter fw = null;
    File file;

    /**
     * Used for creating the file when the object is implemented.
     * @param yourstring
     * @param yourfilename
     * @throws IOException -- file check
     */
    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);
        } catch (IOException e) {
            e.printStackTrace();
        }//allows append to the file without over writing. The TRUE keyword is used for append


    }

    /**
     * Must supply two parmaters. The first parmater is the string that is to be written to the file. The second parmater is used for
     * the file name. The extension C: for the default path.
     * @param yourstring
     * @param yourfilename
     */
    void Error(String yourstring, String lineNumber){

        try{
            pw.println("ERROR: " + yourstring + " * " + timeStamp.toString() +" * " + " Line Number: " + lineNumber + "\n");
        } catch (Exception e) {
            e.printStackTrace();
        }  
    }

    void Debug(String yourstring, String lineNumber){

         try{
             pw.println("DEBUG: " + yourstring + " ******* " + timeStamp.toString() +" ******* " + " Line Number: " + lineNumber + "\n");
         } catch (Exception e) {
             e.printStackTrace();
         }   
   }

   void Info(String yourstring, String lineNumber) {

       try{
           pw.println("INFORMATION: " + yourstring + " ******* " + timeStamp.toString() +" ******* " + " Line Number: " + lineNumber + "\n");
   } catch (Exception e) {
           e.printStackTrace();
       } 
   }

   void Warn(String yourstring, String lineNumber){

       try{
           pw.println("Warning: " + yourstring + " ******* " + timeStamp.toString() +" ******* " + " Line Number: " + lineNumber + "\n");
       } catch (Exception e) {
           e.printStackTrace();
       }    
  }

   void openPrintWriterStream(PrintWriter pw) {
        pw = new PrintWriter(fw);

        try {
            fw = new FileWriter(file, true);
        } catch (IOException e) {
            e.printStackTrace();
        } 
   }

    void closeFile() {
   pw.close();
     }
}

Same null pointer exception:

I changed the code but still receive the same null point exception. I do not even need the PrintWriter pw = null variable?

filePath: C:\Users\home-1\Desktop\
yourfilename: subtract.txt
fileName::--> C:\Users\home-1\Desktop\subtract.txt
file: C:\Users\home-1\Desktop\subtract.txt
java.lang.NullPointerException
    at DDHTestBufferedImage.DDHLogger.Debug(DDHLogger.java:62)
    at DDHTestBufferedImage.SubtractBufferedImage.main(SubtractBufferedImage.java:40)

Upvotes: 2

Views: 2641

Answers (2)

lreeder
lreeder

Reputation: 12206

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.

Upvotes: 2

matt forsythe
matt forsythe

Reputation: 3912

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.

Upvotes: 3

Related Questions