자바 입/출력 객체입/출력

자바 입/출력 객체입/출력


객체 입/출력


  • . 객체단위의 입력과 출력도 마찬가지로 스트림을 기반으로한다.
    한가지 주의할 점은 객체의 입/출력에서는 직렬화(Serializable) 라는 개념이 반드시 필요하다
    직렬화라는것은 클래스의 구성을 파일이나 네트워크로 정상적으로 전달하기 위해
    형태를 재구성하는 것이다 다시말해 일렬로 줄을 지어서 전송하여야 한다는것이다
    자바큭에서는 이러한 번거로움을 해결하기 위하여 java.io.Serializable 이라는
    인터페이스를 제공해 주었다.

  • . 직렬화 구현방법
    전송하고자 하는 객체에 대해 Serializable 를 구현해주기만 하면 되는데
    이 인터페이스 내부에는 재정의 할 메소드도 없다 클래스 선언부에서 [implements Serializable]
    이라고만 적어주면 된다.

  • . 객체 출력

1 . 파일 출력용
File file = new File(“파일명”);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(….);

2 . 네트워크 출력용
Socket soc = new Socket(…..);
BufferedOutputStream bos = new BufferedOutputStream(soc.getOutputStream());
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(….);

  • . 객체 입력

1 . 파일 입력용
File file = new File(“파일명”);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
try{
Object obj = ois.readObject();
}catch(ClassNotFoundException ee){}

2 . 네트워크 입력용
Socket soc = new Socket();
BufferedInputStream bis = new BufferedInputStream(soc.getInputStream());
ObjectInputStream ois = new ObjectInputStream(bis);
try{
Object obj = ois.readObject();
}catch(ClassNotFoundException ee){}

Ex 1 )

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.*;

class Round16_Ex12_Sub implements Serializable {
// 출력 대상이 되는 클래스는 반드시 java,io.Serializable을 구현해야 한다
int x;
int y;
}

public class Round16_Ex12 {
public static void main(String[] ar) throws IOException {
Round16_Ex12_Sub ap = new Round16_Ex12_Sub();
ap.x = 100;
ap.y = 200;
// 출력 대상 객체를 생성하고 x와 y의 값을 적절하게 변경한다
File dir = new File("C:\\java\\work");
File file = new File(dir, "object.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(bos);
// 출력 대상에 대한 Stream객체를 ObjectOutputStream으로 생성한다.
oos.writeObject(ap);
// ap라는 객체를 파일로 전송한다.
}
}

ex 2 )

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
import java.io.*;

public class Round16_Ex13 {
public static void main(String[] ar) throws IOException {
File dir = new File("c:\\java\\work");
File file = new File(dir, "object.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
// 위의 예제에서 생성한 Object.txt.파일에 대한 입력 Stream을 ObjectInputStream
// 의 객체형태로 생성한다.
Object obj = null;
try {
obj = ois.readObject();
// 저장되어 있는 객체를 Object 형태로 입력밭는다. 이때 해당 클래스를 찾을수 없을 경우
// 예외를 처리해 주어야 한다.
} catch (ClassNotFoundException ee) {
}
ois.close();
// 불러온 객체를 Object type으로 담은후 InputStream을 닫는다.
Round16_Ex12_Sub ap = (Round16_Ex12_Sub) obj;
// 전달된Object의 원래 형태가 Round16_Ex12_sub 이므로 강제 형변환을 해준다 .
System.out.println("x = " + ap.x);
System.out.println("y = " + ap.y);
}
}

Ex 3 )

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

/*
친구의 정보를 이름, 주민번호, 전화번호, 주소 등으로 하고 그 클래스를 파일에 저장하는 예제
*/
import java.io.*;

public class Round16_Ex14 implements Serializable {
// 객체를 전달하는대에 직렬화가 필요하므로 Serializable을 implements시켰다
private String name;
private String jumin;
private String tel;
private String addr;
private static transient BufferedReader in;
static {
in = new BufferedReader(new InputStreamReader(System.in));
}

// System에서 입력받은 값을 String값에 담는다
public Round16_Ex14() throws IOException {
System.out.print("name = ");
name = in.readLine();
System.out.print("jumin = ");
jumin = in.readLine();
System.out.print("tel = ");
tel = in.readLine();
System.out.print("addr = ");
addr = in.readLine();
}

public void disp() {
System.out.println(name + "\t");
System.out.println(jumin + "\t");
System.out.println(tel + "\t");
System.out.println(addr);
}
}


import java,io.*;
import java.util.*;
public class Round16_Ex15 {
public static void main (String[] ar) throws ClassNotFoundException, IOException {
File dir = new File("C:\\java\\work");
File file = new File(dir, "myfriends.txt");
//File 객체를 생성
Vector vc = new Vector();
//객체를 담을 Vector의 객체선언
if(file.exists()){//만약 파일이 있다면
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
vc = (Vector) ois.readObject();
//만약 기존에 파일이 존재한다면 프로그램 시작시에 읽어들인다. 따라서 프로그램이
//종료되더라도 다음에 프로그램을 시작할 때에 기존에 등록된 데이터들을 그대로 이용할 수있다
ois.close();
//파일을 읽어온 값을 Vector값에 담은후에 ObjectInputStream을 닫는다.
}
while(true) {
System.out.print("1. 친구등록 2.전체보기 3.종료 = ");
int x = System.in.read() - 48;
System.in.read();
System.in.read();
if(x == 1) {
Round16_Ex14 ps = new Round16_Ex14();
vc.add(ps);
//생성자로 입력받는부분 호출 입력한 값의 객체를 Vector에 담는다.
System.out.println("친구 1명을 등록했습니다. ");
} else if(x == 2){
for(int i = 0; i<vc.size(); i++ ) {
Round16_Ex14 imsi = (Round16_Ex14) vc.elementAt(i);
imsi.disp();
}
//Vector로 담았던 객체를 하나씩 불러내어 화면에 출력한다.
//이미 disp();라는 메서드가 작성되어 있으므로 출력된다.
} else if(x == 3){
ObjectOutputStream oos = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(file)));
oos.writeObject(vc);
oos.close();
//종료하기를 누르면 Vector에 저장되어 있던 값들이 ObjectOutputStream으로
//객체로서 저장되어 파일에 전송한다. 객체형으로 전송하므로 가져올때도 객체형으로
//가져와야 한다
System.exit(0);
} else{
System.out.println("잘못입력");
}
}
}
}

`

Share