1

I'm making a chat server for a class and am having issue logging messages for offline users. The data appends to the logfile as an object, it grows in size as you log more. When I login as the user who received a message it only returns the first message sent. I've spent a lot of time with this can can't figure out what I'm missing.

The input:

 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");
  }

The Output:

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");
}
}
Joshua
  • 9
  • 2

1 Answers1

1

I don't think you can just append to an ObjectOutputStream like that. I think it would be possible if you do this:

For output, keep appending messages as you do now.

For input, open file as a byte input stream. Wrap this in a ObjectInputStream. When that object input stream has no more date, discard it, check the original byte input stream for more data, if it has more, then create a new ObjectInputStream and read data from that. Repeat until no more data exists in byte input stream.

There might be issues with ObjectInputStream consuming data not belonging to it.

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53