If you serialize it to a linear array list, you can return it back to the linear array list when you deserialize it - all other methods did not help me:
import java.io.*; import java.util.ArrayList; import java.util.Arrays; public class Program { public static void writeToFile(String fileName, Object obj, Boolean appendToFile) throws Exception { FileOutputStream fs = null; ObjectOutputStream os = null; try { fs = new FileOutputStream(fileName); os = new ObjectOutputStream(fs); //ObjectOutputStream.writeObject(object) inherently writes binary os.writeObject(obj); //this does not use .toString() & if you did, the read in would fail } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try { os.close(); fs.close(); } catch(Exception e) { //if this fails, it probably open, so just do nothing } } } @SuppressWarnings("unchecked") public static ArrayList<Person> readFromFile(String fileName) { FileInputStream fi = null; ObjectInputStream os = null; ArrayList<Person> peopleList = null; try { fi = new FileInputStream(fileName); os = new ObjectInputStream(fi); peopleList = ((ArrayList<Person>)os.readObject()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch(EOFException e) { e.printStackTrace(); } catch(ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try { os.close(); fi.close(); } catch(Exception e) { //if this fails, it probably open, so just do nothing } } return peopleList; } public static void main(String[] args) { Person[] people = { new Person(1, 39, "Coleson"), new Person(2, 37, "May") }; ArrayList<Person> peopleList = new ArrayList<Person>(Arrays.asList(people)); System.out.println("Trying to write serializable object array: "); for(Person p : people) { System.out.println(p); } System.out.println(" to binary file"); try { //writeToFile("output.bin", people, false); //serializes to file either way writeToFile("output.bin", peopleList, false); //but only successfully read back in using single cast } // peopleList = (ArrayList<Person>)os.readObject(); // Person[] people = (Person[])os.readObject(); did not work // trying to read one at a time did not work either (not even the 1st object) catch (Exception e) { e.printStackTrace(); } System.out.println("\r\n"); System.out.println("Trying to read object from file. "); ArrayList<Person> foundPeople = null; try { foundPeople = readFromFile("input.bin"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (foundPeople == null) { System.out.println("got null, hummm..."); } else { System.out.println("found: "); for(int i = 0; i < foundPeople.size(); i++) { System.out.println(foundPeople.get(i)); } //System.out.println(foundPeople); //implicitly calls .toString() } } }
source share