如何对数据进行序列化和反序列化,然后传输到 ArrayList 中?

huangapple go评论82阅读模式
英文:

How to (de)serialize and transfer data obtained to an ArrayList?

问题

我正在尝试对一个名为 "people.dat" 的简单序列化文件进行序列化和反序列化操作,该文件包含人员数据("Name"、"age"、"mail" 等),然后将所有行(person1 数据、person2 数据等)传输到一个 ArrayList 中。类似于以下示例代码:

import java.io.*;
import java.util.*;

class People implements Serializable {
    protected String _name;
    protected int _age;
    protected String _mail;
    protected String _comments;
    
    public People(String name, int age, String mail, String comments) {
        _name = name;
        _age = age;
        _mail = mail;
        _comments = comments;
    }
}

public class Example {
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        if (new File("people.dat").exists()) {        
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("people.dat"));
                ArrayList<People> p = new ArrayList<People>();
                p = (ArrayList<People>) ois.readObject();
                System.out.println("Array size is: " + p.size());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

在代码的以下部分会发生 "ClassNotFoundException" 错误:

p = (ArrayList<People>) ois.readObject();

我的问题是:

1- 我做错了什么?
2- 对于初学者来说,将数据从 .dat 文件传输到 ArrayList 中,最佳方法是什么?

谢谢。

英文:

I'm trying to (de)serialize a simple serialized file called "people.dat" which contains people data ("Name", "age", "mail",...) and transfer all the lines (person1 data, person2 data,..) to an ArrayList. <p>Something like this:


import java.io.*;
import java.util.*;

class People implements Serializable{
	protected String _name;
	protected int _age;
	protected String _mail;
	protected String _comments;
	
	public People(String name, int age, String mail, String comments) {
		_name = name;
		_age = age;
		_mail = mail;
		_comments = comments;
	}}


public class Example {
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		// TODO Auto-generated method stub
		if (new File(&quot;people.dat&quot;).exists()) {		
			try {
				ObjectInputStream ois = new ObjectInputStream (new FileInputStream(&quot;people.dat&quot;));
				ArrayList&lt;People&gt; p = new ArrayList&lt;People&gt;();
				p = (ArrayList&lt;People&gt;) ois.readObject();
		        System.out.println(&quot;Array size is: &quot; + p.size());
		    }catch (Exception e){
		      e.printStackTrace();
		    }
		}}}


It sends me the "ClassNotFoundException" in line

p = (ArrayList&lt;People&gt;) ois.readObject();

My questions are:

1- What am I doing wrong?<p>
2- Which would be the best way (for a beginner) to pass those data from the .dat file -> to the ArrayList?

Thanks..

答案1

得分: 0

可能的原因是,在序列化类Person时,其类路径与您尝试反序列化时的类路径不同。

例如会导致错误的情况:

  • 在序列化时,Person类的类路径为app.package.Person
  • 在尝试反序列化时,Person类的类路径变为app.Person

这会导致问题,因为在序列化文件中会写入“原始”的类路径。

另外,您确切地序列化了什么?一个包含Person对象的ArrayList吗?还是只是一个Person对象,而您正尝试直接将其反序列化到ArrayList中(这是不可能的)?

如果您想将某个对象反序列化为ArrayList,则该对象必须是已序列化的ArrayList!(是的,您可以对ArrayList进行序列化,因为它只是一个类!)

英文:

A possible reason would be that the class path of the class Person was different when you serialized it then when you try to deserialize it. <br>
<br>
Exemple that would throw an error : <br>

  • The class path of Person was app.package.Person when serialized
  • The class path of Person is now app.Person when trying to deserialize

This would not work because in your serialized file, the "raw" class path is written.

Also, what did you serialize exactly ? An ArrayList containing Persons ? Or just a Person and you're trying to deserialze it directly inside an ArrayList (which in not possible) ?

If you want to deserialize something into an ArrayList, this something has to be an ArrayList that was serialized ! (Because yes you can serialize an ArrayList as it is just a class !)

huangapple
  • 本文由 发表于 2020年10月22日 18:02:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64479919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定