简体   繁体   中英

Cannot write to file ArrayList with class objects

I've reasearched a lot of websites and I couldn't find answear. I'm trying to write to .txt file my ArrayList which constains class objects. Every time I try to do it I`m getting exception. With reading is the same problem. Here is my code:

public static void write()
{
    try 
    {
        FileOutputStream out = new FileOutputStream("clients.txt");
        ObjectOutputStream oout = new ObjectOutputStream(out);
        oout.writeObject(lista);
        oout.close();
    }
    catch(Exception ioe)
    {
        System.out.println("writing Error!");
        welcome();
    }
}
public static void read()
{

    try
    {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("clients.txt"));
        lista = (List<Client>) ois.readObject();
    }
    catch (ClassNotFoundException ex) 
    {
        System.out.println("Koniec pliku");
    }
    catch(IOException ioe)
    {
        System.out.println("Error!");
        welcome();
    }
}

I guess you're looking for the Serializable interface of Java. In order to save objects you're class have to implement it.

The question is: What execatly do you want to save? The content of the list so that you can save it in a file and load it afterwards?

This simple example works for me (for the scenario I mention above):

public class User implements Serializable {
   private static final long serialVersionUID = 1L;

   private String name;
   private int age;

   public User(String name, int ag) {
      this.name = name;
      this.age = age;
   }

   @Override
   public String toString() {
     return (this.name + ' ' + this.age);
   }
}
public class Main {
   private static List<User> l;

   public static void main(String[] args) {
     l = new ArrayList<User>();
     user1 = new User("John", 22);
     user2 = new User("Jo", 33);
     l.add(user1);
     l.add(user2);
     write();
   }

   public static void write() {
      try {
        FileOutputStream fos = new FileOutputStream("testout.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(l);
        oos.close();
    } catch (Exception ioe) {
        System.out.println("writing Error!");

    }
  }
}

Ok I have changed a bit (not each function just the read and write functionality) and this work. Link to Code . One important thing is that the Scanner class is not serializable. Therefore, you have to make it static for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM