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 ");

Your test data does not show you writing the ArrayList to the file. The exception is telling you that the data is the file looks like a single String.
It may be a good idea to delete that file, and use your writeFile method to write an arraylist to tghe file before trying the read again.
ps: Object streams write & read data in binary format - they are definitely NOT text files

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.