串行化的问题

fk1998 2003-08-30 09:23:32
谁能解释一下串行化?具体应用?举个例子?
...全文
52 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
star821116 2003-08-30
  • 打赏
  • 举报
回复
就是把类以字节流的形式写入到磁盘或者IO设备,下面是一个例子,很简单的:
import java.io.*;
import java.util.*;

/** Demonstrate use of Serialization. */
public class SerialDemo {
protected static final String FILENAME = "serial.dat";

public static void main(String[] s) throws IOException {
new SerialDemo().save();
new SerialDemo().dump();
}

/** The save method in an appliction */
public void save() throws IOException {
ArrayList v = new ArrayList();
// Gather the data
MyData u1 = new MyData("Ian Darwin", "secret_java_cook");
v.add(new Date());
v.add(u1);
v.add(new MyData("Abby Brant", "dujordian"));
write(v);
}

/** Does the actual serialization */
public void write(Object theGraph) throws IOException {
// Save the data to disk.
ObjectOutputStream os = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(FILENAME)));
os.writeObject(theGraph);
os.close();
}

public void dump() throws IOException {
ObjectInputStream is = new ObjectInputStream(
new FileInputStream(FILENAME));
System.out.println(is.readObject());
is.close();
}
}

/** Simple data class to be serialized. */
class MyData implements Serializable {
String userName;
String passwordCypher;
transient String passwordClear;
public MyData(String name, String clear) {
userName = name;
// Save the clear text p/w in the object, it won't get serialized
passwordClear = clear;
// So we must save the encryption! Encryption not shown here.
passwordCypher = DES.encrypt(passwordClear);
}
}

/** More of the demo; this just generates a String; Strings are serializable */
class DES {
// Obviously just a placeholder.
public static String encrypt(String s) {
return s;
}
}

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧