Serializable对象中的NullPointerException

时间:2014-12-10 23:50:24

标签: java serialization nullpointerexception symbols jgrasp

这是一个大学课程作业,它创建一个ItemRecord类并使用getter和setter实现Serializable,然后覆盖toString方法。接下来,我创建了一个ItemRecordReport类,其中Scanner对象映射到输入文件“ItemRecord_text.txt”。创建了映射到二进制输出文件“ItemRecord_binary.txt”的ObjectOutputStream对象。创建了映射到二进制文件的ObjectInputStream对象。一切正常。我通过在方法main中放入一个数组并使用附加的文本文档更改字段值来修改此帖子。我的错误是NullPointerException:这是堆栈跟踪

Item   Cost     Quantity  Description
Number
A100  $ 99.99   10        Canon PowerShot-135
A200  $149.99   50        Panasonic-Lumix T55
A300  $349.99   20        Nikon- D3200 DSRL
A400  $280.99   30        Sony- DSC-W800
A500  $ 97.99   20        Samsung- WB35F
Exception in thread "main" java.lang.NullPointerException
at ItemRecordReport.endRecord(ItemRecordReport.java:165)
at ItemRecordReport.main(ItemRecordReport.java:156)

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

//创建程序,以便类的对象可以序列化,实现接口Serialiable //使用4个参数创建构造函数,并附带get和set方法,Override toString方法 //创建包含5条记录的文本文件,创建Scanner对象,ObjectOutputStream和ObjectInputStream //创建新的ItemRecord对象,使用对象的set方法更改ItemRecord对象中所有字段的值 //使用toString方法修改ItemRecord对象

 import java.io.Serializable;
 public class ItemRecord implements Serializable

 {  //declare 4 fields with private access
 private String itemNumber;
 private double cost;
 private int quantity;
 private String description;


 //constructor with no arguments call other constructor with default values
 public ItemRecord()
 {
 this("",0.0,0,"");

 }//end constructor with no arguments
//constructor with 4 arguments
public ItemRecord(String number, double price, int quant, String desc)
{
  setItemNumber(number);
  setCost(price);
  setQuantity(quant);
  setDescription(desc);
 }//end constructor

 public void setItemNumber(String number)
 {
  itemNumber = number;
 }//end setItemNumber
 public String getItemNumber()
 {
  return itemNumber;
 }//end getItemNumber

 public void setCost(double price)
{
  cost = price;
}//end seCost
public double getCost()
{
  return cost;
}//end getCost

public void setQuantity(int quant)
{
  quantity = quant;
}//end setQuantity
public int getQuantity()
{
  return quantity;
}//end getQuantity

public void setDescription(String desc)
{
  description = desc;
}//end setDescription
public String getDescription()
{
  return description;
}//end getDescription
public static void printHeading()
{
System.out.println("Item   Cost     Quantity  Description");
System.out.print("Number");
System.out.println();
}

public String toString()
{
 return this.getItemNumber()+String.format("  $%6.2f   ",+this.getCost())+String.format("%4d       ",+this.getQuantity())+this.getDescription();
}
}//end class ItemRecord

以下是另一个测试类:此类包含ObjectOutputStreamObjectInputStream个对象。因此,方法main和我用来调用main中方法的ItemRecordReport对象。

import java.io.*;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Scanner;

public class ItemRecordReport
{  private ObjectOutputStream output;//writes to binary 
private ObjectInputStream binInFile;//reads binary
private Scanner input;

public void openInputBinaryFile()
 {//create a ObjectInputStream object that will read a binary file
  try
  {
    binInFile  = new ObjectInputStream(new FileInputStream("ItemRecord_binary.txt"));

  }//end try
  catch (IOException ioException)
  {
     System.out.println("Error opening file.");
  }//end catch 
  }//end openInputBinaryFile

  public void openOutputBinaryFile()
  {  
 //creating a binary objectOutputStream text file
  try
  {
     output = new ObjectOutputStream(
     new FileOutputStream("ItemRecord_binary.txt"));
   }//end try
   catch (IOException ioException)
   {
     System.err.println("Error opening file");
  }

  }//end openOutputBinaryFile
  public void readInputTextRecords()
  {
     ItemRecord record;
     String itemNumber;
     double cost;
     int quantity;
     String description;


     try
     {
       input  = new Scanner(new File("ItemRecord_text.txt"));
     }

      catch (IOException e)
     {
        System.out.println("Error file not found");
     }//end catch

      while(input.hasNext())
        {
        try{
              itemNumber = input.next();
              cost = input.nextDouble();
              quantity = input.nextInt();
              description = input.nextLine();

              record = new ItemRecord(itemNumber,cost,quantity,description);

              //writing into the binary text file
              output.writeObject(record);
           }

           catch (IOException ioException)
           {
              System.out.println("Error writing to binary file.");
              return;
           }
        }  
    }//end readInputRecords

   public void readInputBinaryRecords()
   {
     openInputBinaryFile();
     ItemRecord otherRecord;

     try
     {   while (true)
        {
           otherRecord = (ItemRecord) binInFile.readObject(); //use down cast
           System.out.println(otherRecord.toString());
        }
     }
      catch (EOFException e)
     {
        return;
     }//end catch
      catch (ClassNotFoundException e)
     {
        System.err.println("Unable to create object.");
     }//end catch 
     catch (IOException ioException)
     {
        System.err.println("Error reading from binary file.");
     }//end catch 

   }//readInputBinaryRecords
   public void closeBinaryOutputFile()
  {
  try
  {  if (output !=null )
        output.close();
  }//end try
  catch ( IOException ioException)
  {
     System.out.println( "Error closing file");
     System.exit(1);
  }//end catch
   }//end closeBinaryOutputFile

  public void closeBinaryInputFile()
 {
  try
  {  if (binInFile != null )
        binInFile.close();
     else
        System.out.println("No records were written to the binary file!");
  }//end try
  catch ( IOException ioException)
  {
     System.out.println( "Error closing file");
     System.exit(1);
  }//end catch
  }//end closeBinaryFile

 public static void main(String[] args)
{
 ItemRecordReport object = new ItemRecordReport();

 ItemRecord.printHeading();//print heading
 object.openOutputBinaryFile();//opens the binary file
 object.readInputTextRecords();//reads text file and writes to binary file
 object.closeBinaryOutputFile();//closes the binaryOutputFile

 object.openInputBinaryFile();//opens binary file
 object.readInputBinaryRecords();
 object.closeBinaryInputFile();
 Scanner inFile;
 ItemRecord[] itemRecord = new ItemRecord[5];


  itemRecord[x] = new ItemRecord();


  for (int x = 0; x <= 4; x++){
     itemRecord[x].setItemNumber("");
     itemRecord[x].setCost(0);
     itemRecord[x].setQuantity(0);
     itemRecord[x].setDescription("");
  }

  try
  {
     inFile = new Scanner(new File("itemRecord.txt"));

     while(inFile.hasNext())
      {
      for(int count =0; count<=4; count++)
        {
          itemRecord[count].setItemNumber(inFile.next());
          itemRecord[count].setCost(inFile.nextDouble());
          itemRecord[count].setQuantity(inFile.nextInt());
          itemRecord[count].setDescription(inFile.next());

     }//end for loop 
   }//end while

  }
  catch (IOException e)
  {
     System.out.println("Error file not found");
  }//end catch
  try
  {
  ObjectOutputStream binOutFile = new ObjectOutputStream
  (new FileOutputStream("ItemRecord_binary.txt"));
  }//end try
  catch (IOException e)
  {
  System.err.println("error opening file");
  }
  System.out.println(itemRecord.toString());



 }//end method main 



}//end class ItemRecordReport

这是文本文件:

A100 99.99 10 Canon PowerShot-135
A200 149.99 50 Panasonic-Lumix T55
A300 349.99 20 Nikon- D3200 DSRL
A400 280.99 30 Sony- DSC-W800
A500 97.99 20 Samsung- WB35F

这是用于更改字段值的新文本文件:

B100 98.00 10 ABC1010
B200 97.00 15 DEF1020
B300 96.00 10 GHI1030
B400 95.00 05 JKL1040
B500 94.00 01 MNO1050

Error stack trace
Item   Cost     Quantity  Description
Number
A100  $ 99.99   10        Canon PowerShot-135
A200  $149.99   50        Panasonic-Lumix T55
A300  $349.99   20        Nikon- D3200 DSRL
A400  $280.99   30        Sony- DSC-W800
A500  $ 97.99   20        Samsung- WB35F
Exception in thread "main" java.lang.NullPointerException
at ItemRecordReport.endRecord(ItemRecordReport.java:165)
at ItemRecordReport.main(ItemRecordReport.java:156)

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

1 个答案:

答案 0 :(得分:0)

这里有很多问题。 NullPointerException来自于您已初始化ItemRecord[] 数组而非其任何元素的事实。你需要添加

itemRecord[x] = new ItemRecord();

以上第153行。

然而还有其他问题。

  • 您正在编写自己的错误消息,而不是自己打印更有用的异常消息,或者,当您仍在调试时,打印堆栈跟踪。例如:

    catch (IOException ioException)
    {
        ioException.printStackTrace();
    }
    
  • 您正在捕捉异常并继续进行,就好像它们没有发生一样。取决于try块中代码成功的代码应该在同一个try块中。例如:

    try
    {
        input = new Scanner(new File("ItemRecord_text.txt"));
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }//end catch
    while (input.hasNext())
    // ...
    

    应该是

    try
    {
        input = new Scanner(new File("ItemRecord_text.txt"));
        while (input.hasNext())
        // ...
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }//end catch
    
  • 您无法扫描&#34; ItemRecord.txt&#34;文件正确。它有五列,但您只扫描其中四列。留给读者练习。

  • 我建议你放弃写作的习惯

    } // end catch
    

    等等。现代的IDE和适当的缩进使得这种完整性变得不必要,并且它实际上在实践中受到妨碍,并且它们经常会出错。你可能已经在学校里教过它,你当然应该做你想做的任何事情来获得你想要的成绩,但是在这里人们不会做太多。几十年来,Haven没见过它。