I've been trying to do this for the past two hours I have object of type PersonTest I managed to save the data ,but I'm not sure if it correct or not becouse I still can't read the file. I want to read and write using java Object Stream
this is my write to file method
public void writeFile(Object o){
try {
ObjectOutputStream objOStram = new ObjectOutputStream(new FileOutputStream("//Desktop/test.txt"));
objOStram.writeObject(o);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
when I tried this method I got [] in the output
public void readDataFromFile(File fileName){
try {
// TODO code application logic here
ObjectInputStream pbjInput = new ObjectInputStream(new FileInputStream("//Desktop/" + fileName));
try {
Object p1 = (Object) pbjInput.readObject();
System.out.println(p1);
} catch (ClassNotFoundException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
and when I tried this method I got this error
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList
public void readToList(File fileName) throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectInputStream objectInputStream = new ObjectInputStream(
new FileInputStream("test.txt"));
ArrayList<PersonTest> readObjects = (ArrayList<PersonTest>)objectInputStream.readObject();
}
}
This is how I tested my method
File fName = new File("test.txt");
System.out.println("writing DONE");
System.out.println("reading data");
System.out.println("The file contain the follwoing: ");
d.readToList(fName);
//d.readDataFromFile(fName);
System.out.println("reading DONE ");