1

I am testing an ObjectInputStream in Java. When I include the if statement, I get an EOF error. How do I properly test the object coming into the stream? The input stream object is of type byte[] array.

if (ObjectInputStream.readObject() instanceof byte[]) {
    // what to get the new file
    System.out.println("Getting File");
    fileFromServer = new File("/Users/joshuataylor/git/swd_jtylor/oral_exam2/27-13_FileRetrieve_Easy/src/output.txt");
    byte[] fileContent = (byte[]) ObjectInputStream.readObject();
    System.out.println(fileContent.length);
    Files.write(fileFromServer.toPath(), fileContent);
    ObjectOutputStream.flush();

    message = "End Connection";
    System.out.println("eof");
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • Your instance variables should not start with an uppercase, for once; and certainly not with the same name as an existing class. Also, do you realize that you read twice from the input stream? – fge Nov 19 '15 at 08:08

2 Answers2

1

Currently you are reading two objects via ObjectInputStream.readObject() - one in the condition, and another one inside the if block.

You should call ObjectInputStream.readObject() just once and store it in a variable :

Object obj = ObjectInputStream.readObject();
if (obj instanceof byte[]) {
    // what to get the new file
    System.out.println("Getting File");
    fileFromServer = new File("/Users/joshuataylor/git/swd_jtylor/oral_exam2/27-13_FileRetrieve_Easy/src/output.txt");
    byte[] fileContent = (byte[]) obj;
    System.out.println(fileContent.length);
    Files.write(fileFromServer.toPath(), fileContent);
    ObjectOutputStream.flush();

    message = "End Connection";
    System.out.println("eof");
}
Eran
  • 387,369
  • 54
  • 702
  • 768
0

The readObject() into the "if" condition reads the object, so the next readObject() into the body of the "if" finds it empty.

Even if it has some drawbacks you should wrap it in a try and catch the EOFException and remove the "if". Be aware that many situations could raise that exception, like a truncated file.

try {
  ...
  byte[] fileContent = (byte[]) ObjectInputStream.readObject();
  ...
  }
}
catch (EOFException e){
... // exit the reading loop
}