Serializable Class仅输出第一条记录

时间:2017-05-05 01:42:06

标签: java loops serialization

我试图创建一个循环来显示二进制文件中的所有内容,但它只显示第一件事:

public class ItemRecordReport
{
   static Scanner input; //allows for the scanner to be availble to other methods in the class
   static ObjectOutputStream binOutFile; 
   static ObjectInputStream binInFile;

   public static void main(String args[]) throws IOException, ClassNotFoundException
   {
      // Create a scanner
      try
      {
         input = new Scanner(new File ("ItemRecord_text.txt")); //use scanner input
      } 
      catch (FileNotFoundException fileNotFoundException)
      {
         System.err.println("Error opening file.");
         System.exit(1);
      }
      //create an object output stream
      try
      {
         binOutFile = new ObjectOutputStream (new FileOutputStream("ItemRecord_binary.txt"));
      }
      catch(FileNotFoundException fileNotFoundException)
      {
         System.err.println("Error opening file.");
         System.exit(1);
      }
       //Create an Item Record Object
      ItemRecord record = new ItemRecord("null", 0.0, 0, "null");


      //Create a loop that will read from the file, and store it in an ItemRecord object

      while (input.hasNext() )
      {
         record.setItemNumber(input.next() );
         record.setCost(input.nextDouble() );
         record.setQuantity(input.nextInt() );
         record.setDescription(input.nextLine());


         binOutFile.writeObject(record); //stores the file in binary

      }
      binOutFile.close(); //close the file

      //Create an objectinputstrea
      binInFile = new ObjectInputStream ( new FileInputStream("ItemRecord_binary.txt") );

      //create a loop that stores the binary file in an item record object
      try
      {
         while (true)
         {
         //Reads an obejct from the binary file
            record = (ItemRecord) binInFile.readObject(); //read the object into record

            System.out.println(record.toString() );

         }
       }
      catch (EOFException endOfFileException)
      {
         return;
      }

1 个答案:

答案 0 :(得分:1)

您需要在每次迭代时创建一个 new ItemRecord对象,因为序列化不会重新序列化已经序列化的对象的内容。或者:

  • 使用writeUnshared()代替writeObject()
  • 在每个ObjectOutputStream.reset()之后致电writeObject()