Reads External Events from a binary file. Can also create binary files from a list of external events.
| 20 | * from a list of external events. |
| 21 | */ |
| 22 | public class BinaryEventsReader implements ExternalEventsReader { |
| 23 | /** Extension of binary external events file */ |
| 24 | public static final String BINARY_EXT = ".binee"; |
| 25 | |
| 26 | private ObjectInputStream in; |
| 27 | private int eventsLeft; |
| 28 | |
| 29 | /** |
| 30 | * Constructor. |
| 31 | * @param eventsFile The file where the events are read |
| 32 | */ |
| 33 | public BinaryEventsReader(File eventsFile) { |
| 34 | try { |
| 35 | FileInputStream fis = new FileInputStream(eventsFile); |
| 36 | in = new ObjectInputStream(fis); |
| 37 | // first object should tell the amount of events |
| 38 | eventsLeft = (Integer)in.readObject(); |
| 39 | } catch (IOException e) { |
| 40 | throw new SimError(e); |
| 41 | } catch (ClassNotFoundException e) { |
| 42 | throw new SimError("Invalid binary input file for external " + |
| 43 | "events:" + eventsFile.getAbsolutePath(), e); |
| 44 | } |
| 45 | |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Read events from a binary file created with storeBinaryFile method |
| 50 | * @param nrof Maximum number of events to read |
| 51 | * @return Events in an ArrayList (empty list if didn't read any) |
| 52 | * @see #storeToBinaryFile(String, List) |
| 53 | */ |
| 54 | @SuppressWarnings("unchecked") // suppress cast warnings |
| 55 | public List<ExternalEvent> readEvents(int nrof) { |
| 56 | ArrayList<ExternalEvent> events = new ArrayList<ExternalEvent>(nrof); |
| 57 | |
| 58 | if (eventsLeft == 0) { |
| 59 | return events; |
| 60 | } |
| 61 | |
| 62 | try { |
| 63 | for (int i=0; i < nrof && eventsLeft > 0; i++) { |
| 64 | events.add((ExternalEvent)in.readObject()); |
| 65 | eventsLeft--; |
| 66 | } |
| 67 | if (eventsLeft == 0) { |
| 68 | in.close(); |
| 69 | } |
| 70 | } catch (Exception e) { // FIXME: quick 'n' dirty exception handling |
| 71 | throw new SimError(e); |
| 72 | } |
| 73 | return events; |
| 74 | } |
| 75 | |
| 76 | /** |
| 77 | * Checks if the given file is a binary external events file |
| 78 | * @param file The file to check |
| 79 | * @return True if the file is a binary ee file, false if not |
nothing calls this directly
no outgoing calls
no test coverage detected