1

我正在爲一個班級製作聊天服務器,並且正在爲離線用戶提供問題日誌記錄消息。數據作爲對象追加到日誌文件中,隨着日誌記錄的增多,數據量也隨之增加。當我作爲收到消息的用戶登錄時,它只會返回發送的第一條消息。我花了很多時間,這可以不知道我錯過了什麼。對象輸出和輸入問題,只打印輸入的第一行

輸入:

if (exists) 
    ObjectInputStream in = null; 

    try{ 
    in = new ObjectInputStream(new FileInputStream(uLog)); 
    Message msgs; 
    Object obj = null; 
     while ((obj = in.readObject()) != null) 
     { 
     msgs = (Message) obj; 
     user.writeToUser(new Message("POST", "Offline Message from", msgs.getTo() +" "+ msgs.getText())); 
     } 

    in.close(); 

      }catch (Exception e){//Catch exception if any 
    System.err.println("Error: " + e.getMessage()); 
    } 

    boolean success = uLog.delete(); 

    if (!success) 
    throw new IllegalArgumentException("Delete: deletion failed"); 
    } 

輸出:

if(!usersList.getUserByName(msg.getTo()).getOnlineStatus()) 
{ 
    ObjectOutputStream out; 
    try{ 
    out = new ObjectOutputStream(new FileOutputStream(msg.getTo() + ".log", true)); 
    user.writeToUser(new Message("PRIVATE", user.getUserName(), msg.getTo(), msg.getText())); 
    out.writeObject(new Message("PRIVATE", msg.getTo(), user.getUserName(), msg.getText())); 
    out.close(); 
    } 
catch (IOException e){ 
System.out.println("Exception"); 
} 
} 

回答

1

我不認爲你可以追加到這樣一個ObjectOutputStream。我認爲這是可能的,如果你這樣做:

對於輸出,繼續附加消息,你現在要做的。

對於輸入,打開文件作爲字節輸入流。將其封裝在ObjectInputStream中。當該對象輸入流沒有更多日期時,丟棄它,檢查原始字節輸入流是否有更多的數據,如果它有更多的數據,則創建一個新的ObjectInputStream並從中讀取數據。重複,直到字節輸入流中不再有數據存在。

ObjectInputStream可能會消耗不屬於它的數據。

+0

我不確定如何獲取一個字節輸入並將其包裝到ObjectInputStream中。有關於此的任何提示? – Joshua

+0

你正在做它,FileInputStream是一個InputStream的字節。只是讓你處理它。 –