当前位置: 首页 > 面试题库 >

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

洪胜涝
2023-03-14
问题内容

我编写了一个简单的记录器类,可以使它成为一个实例,它将使我能够将信息写入文件。它在一个示例中工作了一段时间,但是现在抛出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)

问题答案:

通过提供与pw类中的字段同名的参数,可以“遮蔽”
openPrintWriterStream()方法中的pw变量。请参见http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html的“参数名称”部分:

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

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

  1. 正如matt forsythe所建议的那样,请退出将PrintWriter作为openPrintWriterStream()的参数传递,然后仅当它为null时才懒惰地构造它。

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

第二种方法允许您通过删除对的所有调用来清理代码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()或将其设为私有,因为同一包中的类仍可以使用它来创建DDHLoggers,而没有必要的FileFileWriter,将来可能会导致NullPointerExceptions。



 类似资料:
  • 问题内容: 我正在android中做一个应用程序,因此我需要访问com.android.internal.telephony API。现在,我可以访问这些API了,但问题是,无论我在自己的类中调用Class Call.java方法的什么地方,都会抛出。您可以在http://hi- android.info/src/com/android/internal/telephony/Call.java.h

  • 首先,下面的代码片段是Google云项目应用程序的一部分,在我的本地客户机Raspberry Pi 1上运行。为了能够从连接到Pi的传感器向云发送数据,需要授权。所有需要的客户端机密都存储在src/main/resources中的“client_secrets.json”中。 项目层次结构 当试图使用客户端机密来授权时,下面的代码抛出一个NullPointerException。它是类“CmdLi

  • 我对spring boot和JPA相当陌生。我正在做我的学习目的的小项目。 实体类 有线索吗?

  • 问题内容: 在双头链表中,我使用了另一个链接,该链接通过copy构造函数复制到copy 。但是,当我遍历链接列表从后端插入时,它抛出了一个空指针异常。 } 问题答案: 问题似乎出在方法上。您有条件继续前进,直到node 不为null 为止: 当while循环结束时,将指向位置。然后在下一行: 现在为null,下一行: 正在尝试访问,因此是NPE的问题。您需要通过将while循环条件更改为以下内容来

  • 我是struts2框架的新手,当我点击submit按钮时,我得到了空指针预期值,注册表表单值没有传递给Bean类,我在Bean类中打印表单值,它打印了空值,我找不到我的错误,请帮助我。。 指数jsp Struts.xml 动作课 例外

  • 我有4个图像作为按钮,当选择正确的按钮时,会出现一个工作正常的箭头按钮。 我的问题是,我试图更改每个按钮的后台资源以在单击此箭头时进行更改,但我在该行得到一个空指针异常: 我已经在java onCreate中声明了nextArrow按钮- 类别: 日志: XML: 我错过了什么明显的东西吗?