2017-05-05 61 views
-1

我試圖創建一個循環來顯示一個二進制文件的一切的第一個記錄,但它永遠只能顯示第一件事:序列化類只輸出

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; 
     } 
+0

請格式化這個難以辨認的混亂。 – EJP

回答

1

你需要創建一個新由於序列化不會重新序列化已經序列化的對象的內容,因此每次迭代都需要對象ItemRecord。或者:

  • 使用writeUnshared()代替writeObject()
  • 呼叫ObjectOutputStream.reset()每個writeObject()後。