public static final String FILENAME = "cool_file.tmp"; public static void main(String[] args) throws IOException, ClassNotFoundException { String test = "This will work if the objects were written with a single ObjectOutputStream. " + "If several ObjectOutputStreams were used to write to the same file in succession, " + "it will not. – Tom Anderson 4 mins ago"; FileOutputStream fos = null; try { fos = new FileOutputStream(FILENAME); for (String s : test.split("\\s+")) { ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(s); } } finally { if (fos != null) fos.close(); } List results = new ArrayList(); FileInputStream fis = null; try { fis = new FileInputStream(FILENAME); while (true) { ObjectInputStream ois = new ObjectInputStream(fis); results.add(ois.readObject()); } } catch (EOFException ignored) { // as expected } finally { if (fis != null) fis.close(); } System.out.println("results = " + results); }
System.out.println("Nombre del archivo ?"); nArchivo= sc.next(); sc.nextLine(); arreglo=new ArrayList(); try{ FileInputStream fileIn = new FileInputStream(nArchivo); ObjectInputStream in = new ObjectInputStream(fileIn); while(true){ arreglo.add((SuperHeroe) in.readObject()); } } catch(IOException i) { System.out.println("no hay mas elementos\n elementos cargados desde el archivo:" ); for(int w=0;w