I'm trying to write an object on a file, and then to read it from the same file i populated an arraylist of object from a simple text file. i have an EOFException when i'm trying to write on file
public class CaricaTestoScriviOggetti_Copia {
public static void main(String[] args) {
File fileIn = new File("src/Lista.txt");
Scanner input = null;
try {
input = new Scanner(fileIn);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Persona> persone = new ArrayList<Persona>();
ArrayList<Persona> maggiorenni = new ArrayList<Persona>();
String nome = null;
String cognome = null;
int eta = 0;
while (input.hasNext()) {
nome = input.next();
cognome = input.next();
eta = input.nextInt();
if (input.hasNext("\n"))
input.nextLine();
persone.add(new Persona(nome, cognome, eta));
}
for (Persona p : persone) {
System.out.println(p);
if (p.getEta() > 17)
maggiorenni.add(p);
}
input.close();
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("src/ListaObj.dat");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos = new ObjectOutputStream(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Persona p : maggiorenni) {
try {
oos.writeObject(p);
oos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// END FOR
try {
fos.close();
oos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileOutputStream fos2 = null;
ObjectOutputStream oos2 = null;
try {
fos2 = new FileOutputStream("src/Oggetto.dat");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos2 = new ObjectOutputStream(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos2.writeObject(maggiorenni.get(1));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos2.close();
oos2.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("src/Oggetto.dat");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois = new ObjectInputStream(fis);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Persona catched = null;
try {
catched = (Persona) ois.readObject();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// END FOR
try {
fis.close();
ois.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("<------------Oggetto Letto------------>");
System.out.println(catched);
// END MAIN
}
// END CLASS
}