写了个简单代码演示了一下序列化的用途;
参考一下;- package test.bean;
- import java.io.Serializable;
- public class SerializableBean implements Serializable{
- private static final long serialVersionUID = 1L;
- private String test;
- public String getTest() {
- return test;
- }
- public void setTest(String test) {
- this.test = test;
- }
-
- }
复制代码 注意必须实行序列化接口;
测试类;- package test.bean;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- public class FoutSerialiable {
- public static final String path = "c:\\1.txt";
- public static void main(String[] args) throws IOException {
- /** 序列化到本地代码 */
- SerializableBean bean = new SerializableBean();
- bean.setTest("PANZERLEADER");
- writeObject(bean);
- /**
- ** 读序列化1.txt代码 SerializableBean bean = readObject();
- * System.out.println(bean.getTest());
- */
- }
- public static SerializableBean readObject() {
- ObjectInputStream in = null;
- try {
- in = new ObjectInputStream(new FileInputStream(path));
- return (SerializableBean) in.readObject();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return null;
- }
- public static void writeObject(SerializableBean bean) {
- ObjectOutputStream out = null;
- try {
- out = new ObjectOutputStream(new FileOutputStream(path));
- out.writeObject(bean);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if (out != null)
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
复制代码 先运行后查看c盘目录1.txt,你会发现
sr 32test.bean.SerializableBean L testt Ljava/lang/String;xpt PANZERLEADER
然后读取,你会发现对象其实已经被你写到了文件中···感谢,看到希望有用,谢谢 |