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"));
        } 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();
        } 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: ");

    System.out.println("reading DONE ");
4 Years
Discussion Span
Last Post by JamesCherrill

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.