Move the reading of the leader into hasNext. Otherwise next() might fail. Considerin...
[marc4j.git] / src / org / marc4j / MarcStreamReader.java
index 9b6f637..3abfc1e 100644 (file)
@@ -85,6 +85,7 @@ public class MarcStreamReader implements MarcReader {
 \r
     private boolean setBadIndicators = true;\r
 \r
+    byte[] leaderBuffer;\r
     /**\r
      * Constructs an instance with the specified input stream.\r
      */\r
@@ -108,8 +109,18 @@ public class MarcStreamReader implements MarcReader {
      * Returns true if the iteration has more records, false otherwise.\r
      */\r
     public boolean hasNext() {\r
-        try {\r
-            if (input.available() == 0)\r
+      int available;\r
+      try {\r
+          available = input.available();\r
+          try {\r
+            leaderBuffer = new byte[24];\r
+            input.readFully(leaderBuffer);\r
+          } catch (EOFException eof) {\r
+            // If we are not capable of reading the leader before EOF, we cannot read a record\r
+            // This happens when we read gzipped marc files, that it returns available bytes, but none is present\r
+            available = 0;\r
+          }\r
+            if (available == 0)\r
                 return false;\r
         } catch (IOException e) {\r
             throw new MarcException(e.getMessage(), e);\r
@@ -127,14 +138,10 @@ public class MarcStreamReader implements MarcReader {
         record = factory.newRecord();\r
 \r
         try {\r
-\r
-            byte[] byteArray = new byte[24];\r
-            input.readFully(byteArray);\r
-\r
-            int recordLength = parseRecordLength(byteArray);\r
+            int recordLength = parseRecordLength(leaderBuffer);\r
             byte[] recordBuf = new byte[recordLength - 24];\r
             input.readFully(recordBuf);\r
-            parseRecord(record, byteArray, recordBuf, recordLength);\r
+            parseRecord(record, leaderBuffer, recordBuf, recordLength);\r
             return(record);\r
         }\r
         catch (EOFException e) {\r