繁体   English   中英

是否建议序列化和反序列化存储在arrayList中的对象?

[英]Is it recommended to serialize & deserialize objects that are stored in arrayList?

在我的小银行应用程序中,用户必须输入一些值(名称,SSN,数量等),并将它们存储在arrayList中。 arrayList大小是动态的。

但是这个问题是我终止应用程序后会丢失所有数据。 这让我想到了编写和读取文件(文件I / O)的实现。

现在我也已经了解了一些叫做序列化和反序列化的东西,虽然我不太确定在什么情况下需要实现它。

在我的特定情况下我是否需要它,或者只是写入和从文件中读取就足够了?

序列化和反序列化与文件I / O有什么关系?

[注意:如有必要,我会提供更多信息]

这是数据库出现的地方。 首先,您可以使用MySQL DB - 它是适用于中小型企业应用程序的优秀免费数据库。 之后,如果您打算将应用程序部署到生产环境 - 具有大量用户和高级功能,并准备为其付出代价 - 您可能会考虑其他数据库,如Oracle等。

对于任何实际应用,不建议将信息存储到文件((De)序列化)。

序列化是一种机制,其中对象可以表示为包含对象数据的字节序列,以及有关对象类型和对象中存储的数据类型的信息。

ArrayList已经实现了Serializable,因此在您的示例中,您可以编写如下内容:

 ArrayList<String> al=new ArrayList<String>();
 al.add("Jean");
 al.add("Pierre");
 al.add("John");

 try{
  FileOutputStream fos= new FileOutputStream("myfile.txt");
  ObjectOutputStream oos= new ObjectOutputStream(fos);
  oos.writeObject(al);
  oos.close();
  fos.close();
 }catch(IOException ioe){
  ioe.printStackTrace();
 }

这里我们将列表al保存在文件myfile.txt中。

要读取文件并返回ArrayList,您将使用ObjectInputStream:

FileInputStream fis = new FileInputStream("myfile.txt");
ObjectInputStream ois = new ObjectInputStream(fis);

ArrayList<String> list = (ArrayList<String>) ois.readObject();

ois.close();

如果要将自己的类的实例写入文件,则需要序列化。 在您的情况下,您可以创建一个java类来保存有关customer的所有值,然后重写hashCode()和equals(),然后将您的对象写入文件。 http://www.tutorialspoint.com/java/java_serialization.htm

此外,如果需要,您可以将单个字段存储在文件以及intString

虽然我建议使用数据库来存储所有这些信息。 但似乎你是一名学生,仍处于学习阶段。 因此,立即与DB交互可能不是一个好方法。

Yes, you can use arraylist for serialization and deserialization. 
Whenever u want to write and read the object into file and from file
respectively then u need to be object should be serialized and object 
write into the file in byte stream format.that means ur data will be secure in 
stream.you can used serialization interface:-
To persist data for future use.
To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
To "flatten" an object into array of bytes in memory.
To exchange data between applets and servlets.
To store user session in Web applications.
To activate/passivate enterprise java beans.
To send objects between the servers in a cluster.
and more............

暂无
暂无

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

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