package u7; import java.io.*; import utils.*; public class ESortUtils { /** * Converts file of Item objects into file that stores numbered lines * of the string representation of that objects. */ public static void convertToText(String fname, String nName) { try { FileInputStream istream = new FileInputStream(fname); ObjectInputStream p = new ObjectInputStream(istream); FileOutputStream ostream = new FileOutputStream(nName); OutputStreamWriter w = new OutputStreamWriter(ostream); Item item; item = readObject(p); int i = 0; while(item != null) { w.write("Item[" + i + "] == " + item + "\r\n"); i++; item = readObject(p); } istream.close(); w.flush(); ostream.close(); System.out.println("Items saved to file " + nName); } catch (Exception ex) { System.out.println("[printFile] Exception in pritnFile caught:"); ex.printStackTrace(); throw new RuntimeException("Exception in [ESortUtils][printFile] " + ex.getMessage()); } } /** Reads an Item object from the object input stream */ public static Item readObject(ObjectInputStream ois) { Item result; try { result = (Item) ois.readObject(); } catch (IOException ex) { System.out.println("[readObject] IOException caught: " + ex.getMessage()); result = null; } catch (ClassNotFoundException ex) { System.out.println("[readObject] ClassNotFoundException caught: " + ex.getMessage()); throw new RuntimeException("Exception in [ESortUtils][readObject] " + ex.getMessage()); } return result; } /** * Reads elements from the input stream into the buffer 'items'. * Returns the number of elements that were loaded. */ public static int load(Item[] items, ObjectInputStream ois) { int iSize = 0; while (iSize < items.length) { try { items[iSize] = (Item) ois.readObject(); iSize++; } catch (IOException ex) { break; } catch (ClassNotFoundException ex) { System.out.println("[readObject] ClassNotFoundExceptioncaught: " + ex.getMessage()); throw new RuntimeException("Exception in [ESortUtils][load] " + ex.getMessage()); } } return iSize; } /** * Saves the elements from the buffer 'items'. * @param iSize the number of elements to be saved. */ public static void writeBuffer(ObjectOutputStream p, Item[] items, int iSize) { try { for (int i=0; i < iSize; i++) { p.writeObject(items[i]); } } catch (IOException ex) { System.out.println("[writeBuffer] exception caught:"); ex.printStackTrace(); throw new RuntimeException("Exception in [ESortUtils][writeBuffer] " + ex.getMessage()); } } }