티스토리 뷰

직렬화(Serializable)란?


객체가 가진 데이터들을 순차적인 데이터로 변환하는 것


데이터가 받는 입장에서는 순서를 알수 없기 때문에 직렬화를 통해 순서대로 보내게 된다.


<예제>


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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
class Car implements Serializable{
    private String color;
    private int speed;
    private int mileage;
    
    public Car(String color, int speed, int mileage) {
        this.color = color;
        this.speed = speed;
        this.mileage = mileage;
    }
    
    
    @Override
    public String toString() {
        return "Car [color=" + color + ", speed=" + speed + ", mileage=" + mileage + "]";
    }
    
}
 
 
public class ObjectStreamTest{
    public static void main(String[] args) {
        ObjectInput in = null;
        ObjectOutput out = null;
        
        try{
            out = new ObjectOutputStream(new FileOutputStream("object.dat"));
            out.writeObject(new Car("빨강",100,20000));
            out.writeObject(new Car("파랑",200,40000));
            out.writeObject(new Car("노랑",300,60000));
            
            out.flush();
            
            in = new ObjectInputStream(new FileInputStream("object.dat"));
 
            System.out.println(in.readObject());
            System.out.println(in.readObject());
            System.out.println(in.readObject());
        }catch (Exception e) {
            // TODO: handle exception
        }
        finally {
            try{
            if (in != null)
                in.close();
            if (out != null)
                out.close();
            }catch (Exception e) {
                // TODO: handle exception
            }
        }
    }
}
cs

출력 :
Car [color=빨강, speed=100, mileage=20000]
Car [color=파랑, speed=200, mileage=40000]
Car [color=노랑, speed=300, mileage=60000]



!) transient 사용하면 직렬화에서 열외시킬 수 있다.

 private transient int speed;

반응형

'언어 > JAVA' 카테고리의 다른 글

[JAVA] 서버(server)와 클라이언트(client), TCP와 UDP  (0) 2016.09.27
[JAVA] FileWriter, FileReader  (0) 2016.09.26
[JAVA] 데이터 형식 범위  (0) 2016.09.26
[JAVA] 스트림(stream)  (0) 2016.09.26
[JAVA] 정규식  (0) 2016.09.22
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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
26 27 28 29 30 31
글 보관함