简单的记录器类但抛出空指针异常?

时间:2014-01-03 22:16:59

标签: java

我编写了一个简单的记录器类,我可以创建一个实例,它允许我将信息写入文件。它在前面的一个例子中工作但现在抛出一个NULL指针异常错误。我真的不知道为什么会这样。我已经在下面放置了类代码。

班级代码:

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();
        } 
   }
}

空指针异常:

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)

新的和清理代码:

/*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();
     }
}

相同的空指针异常:

我更改了代码,但仍然收到相同的空点异常。我甚至不需要PrintWriter pw = null变量?

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)

2 个答案:

答案 0 :(得分:3)

您的openPrintWriterStream实际上并未影响名为pw的成员变量。此外,由于您在方法的最开始重新分配pw引用(并且不返回更新的引用),因此赋值基本上无效。摆脱pw参数,以便赋值实际更新成员变量。您需要进行检查以确保pw尚未打开。

答案 1 :(得分:2)

通过提供具有相同名称的参数 - pw - 作为类中的字段,您正在“隐藏”openPrintWriterStream()方法中的pw变量。请参阅http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html,“参数名称”部分:

参数可以与类的某个字段具有相同的名称。如果是这种情况,则称该参数遮蔽该字段。阴影字段可能使您的代码难以阅读,并且通常仅在设置特定字段的构造函数和方法中使用。

有几种方法可以解决这个问题:

  1. 正如暗示forsy所暗示的那样,退出将PrintWriter作为参数传递给openPrintWriterStream(),然后只有在它为null时才懒惰地构造它。

  2. DDHLogger(String filePath, String yourfilename)构造函数中初始化PrintWriter,因为您拥有构建PrintWriter所需的所有信息,如下面的代码示例所示。

  3. 第二种方法允许您通过删除对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
    
    }
    

    最后,删除DDHLogger()或将其设为私有,因为同一个包中的类仍然可以使用它来创建没有所需FileFileWriter的DDHLoggers,从而可能导致NullPointerExceptions未来。