Java read stream input object in arraylist?

It is assumed that the method below should read the binary in an arrayList . But getting java.io.EOFException :

  at java.io.ObjectInputStream $ BlockDataInputStream.peekByte (ObjectInputStream.java:2553)
 at java.io.ObjectInputStream.readObject0 (ObjectInputStream.java:1296)
 at java.io.ObjectInputStream.readObject (ObjectInputStream.javahaps50)
 at .... Read (Tester.java:400) 
 at .... main (Tester.java:23)

Line 23 basically just calls the method, line 400 is the while loop. Any ideas?

 private static void Read() { try { ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("/file.bin")); while (objIn.readObject() != null) { list.add((Libreria) objIn.readObject()); } objIn.close(); } catch(Exception e) { e.printStackTrace(); } } 
+6
source share
4 answers

According to other answers, you read the loop twice. Another problem is the null test. readObject() returns only null if you wrote zero, not EOS, so it makes no sense to use it as a loop completion test. The correct completion of the readObject() loop is

 catch (EOFException exc) { in.close(); break; } 
+9
source

The problem is that you call readObject () twice in a loop. Try instead:

 MediaLibrary obj = null; while ((obj = (MediaLibrary)objIn.readObject()) != null) { libraryFromDisk.add(obj); } 
+7
source

You read the object during the test:

 while (objIn.readObject() != null) 

Then you read the following object in:

 libraryFromDisk.add((MediaLibrary) objIn.readObject()); 

So, in one iteration, you should only read one object

 private static void Load() { try { ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("/file.bin")); Object object = objIn.readObject(); while (object != null) { libraryFromDisk.add((MediaLibrary) object); object = objIn.readObject(); } objIn.close(); } catch(Exception e) { e.printStackTrace(); } } 
+4
source

You can try this. Good luck

 private static void Load() { try { ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("/file.bin")); boolean check=true; while (check) { try{ object = objIn.readObject(); libraryFromDisk.add((MediaLibrary) object); }catch(EOFException ex){ check=false; } } objIn.close(); } catch(Exception e) { e.printStackTrace(); } } 
0
source

Source: https://habr.com/ru/post/891387/


All Articles