温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java使用Serializable接口实现序列化的方法

发布时间:2020-05-20 16:23:28 来源:亿速云 阅读:187 作者:鸽子 栏目:编程语言

Serializable接口是一个标记接口,不用实现任何方法,一旦某个类实现了该方法,则该类的对象是可序列化的。

具体步骤:

1、创建一个ObjectOutputStream输出流;

2、调用OjectOutputSteam对象的writeObject ()输出可序列化对象。

public class Person implements Serializable {
	private String name;
	private String age;

	public Person() {
		System.out.println("调用Person的无参构造函数");
	}

	public Person(String name, String age) {
		this.name = name;
		this.age = age;
		System.out.println("调用Person的有参构造函数");
	}

	@Override
	public String toString() {
		// TODO 自动生成的方法存根
		return "Person{'name' :" + name + ",'age' :" + age + "}";
	}
}
public class WriteObject {
	public static void main(String[] args) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person.txt"));
			Person p = new Person("baby", "12");
			oos.writeObject(p);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

输出如下:

aced 0005 7372 0017 7365 7269 616c 697a
6162 6c65 5465 7374 2e50 6572 736f 6e4e
aff9 165f 38dd f602 0002 4c00 0361 6765
7400 124c 6a61 7661 2f6c 616e 672f 5374
7269 6e67 3b4c 0004 6e61 6d65 7100 7e00
0178 7074 0002 3132 7400 0462 6162 79

以上就是java中如何使用Serializable接口实现序列化的详细内容,更多请关注亿速云其它相关文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI