Netty使用
Java序列化案例
import com.mayikt.days01.server.serialize.UserInfo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
public class UserInfoTest {
/**
* 序列化对象到文件
*
* @param fileName
*/
public static void serialize(String fileName) {
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName));
out.writeObject("序列化的日期是:");//序列化一个字符串到文件
out.writeObject(new Date());//序列化一个当前日期对象到文件
UserInfo userInfo = new UserInfo("mayikt", 23);
out.writeObject(userInfo);//序列化一个会员对象
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从文件中反序列化对象
*
* @param fileName
*/
public static void deserialize(String fileName) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
String str = (String) in.readObject();//刚才的字符串对象
Date date = (Date) in.readObject();//日期对象
UserInfo userInfo = (UserInfo) in.readObject();//会员对象
System.out.println(str);
System.out.println(date);
System.out.println(userInfo);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// serialize("D:\\codes\\userInfo.txt");
deserialize("D:\\codes\\userInfo.txt");
}
}
-------资源转载于蚂蚁课堂(www.mayikt.com)