1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import java.io.Serializable; public class Person implements Serializable{ private static final long serialVersionUID = 1L; public String name; public int age; public double money; private static final long serialVersionUID = 1L; public Person(String name, int age, double money) { this .name = name; this .age = age; this .money = money; } @Override public String toString() { return "name is:" +name+ " , age is:" +age+ " , money is:" +money; } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class DemoText01 { public static void main(String[] args) { Person person = new Person( "joinName" , 20 , 100.89 ); //序列化对象 -->只有可序列化的类,对象才能序列化 try { ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream( "d:/save.txt" )); oos.writeObject(person); System.out.println( "保存对象" ); oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; public class DemoText02 { public static void main(String[] args) { try { ObjectInputStream ois = new ObjectInputStream( new FileInputStream( "d:/save.txt" )); Person person = (Person) ois.readObject(); System.out.println(person); ois.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
原文:http://blog.csdn.net/dyllove98/article/details/41089469