繁体   English   中英

无法使用类对象写入文件 ArrayList

[英]Cannot write to file ArrayList with class objects

我已经重新搜索了很多网站,但找不到答案。 我正在尝试将包含类对象的 ArrayList 写入 .txt 文件。 每次我尝试这样做时,我都会遇到异常。 阅读是同样的问题。 这是我的代码:

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

我猜您正在寻找 Java 的Serializable接口。 为了保存对象,您必须实现它。

问题是:您最想保存什么? 列表的内容以便您可以将其保存在文件中并在之后加载?

这个简单的例子对我有用(对于我上面提到的场景):

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

    }
  }
}

好的,我已经改变了一点(不是每个功能只是读写功能)和这项工作。 代码链接 一件重要的事情是 Scanner 类不可序列化。 因此,例如,您必须将其设为静态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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