Notice
														
												
											
												
												
													Recent Posts
													
											
												
												
													Recent Comments
													
											
												
												
													Link
													
											
									| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 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 | 
													Tags
													
											
												
												- transient
 - InputStream
 - 오라클
 - stream
 - 8bit
 - set
 - select
 - Oracle
 - JDBC
 - 상속
 - 예외처리
 - swing
 - Annotaion
 - DB연동
 - 16bit
 - 자바
 - Reader
 - 다이얼로그
 - statement
 - driver
 - where
 - Join
 - Connection
 - Transaction
 - 난수
 - java
 - 조회
 - Serializable
 - DB
 - array
 
													Archives
													
											
												
												- Today
 
- Total
 
오버플로
[Java] ObjectStream 활용 - 객체 내보내기 & 객체 읽기 본문
~전편에 이어서~
ObjectStream을 활용해보자!
# 오늘의 코딩 #
[순서]
1. 먼저 내보낼 객체의 기반이 되는 'MyData' Class를 생성 (Serializable interface를 구현한 클래스)
2. ObjectStream활용을 위한 클래스를 생성하여 write와 read method를 작성/실행해보자
#1. MyData Class
- 사용자 정보를 가지고 있으며 직렬화가 막혀있는 변수가 존재함
package test;
import java.io.Serializable;
/**
 * 사용자의 정보를 가진 클래스
 * @author user
 */
public class MyData implements Serializable{
		
	/**
	 * serialVersionUID : 이 클래스 파일이 JVM 외부로 빠져나갔을 때 파일을 검증하기 위한 용도의 Constant
	 * 객체가 JVM 외부로 나갔을 때 검증하기 위해서 ID를 부여함
	 * 1. 현재 JVM에서 빠져나간 객체임을 검증 가능
	 * 2. 시간에 대한 체크 가능
	 */
	private static final long serialVersionUID = -6444648902030740467L;
	private double height;
	private transient double weight; // 직렬화를 막기 위해서는 transient를 걸자 (직렬화 방지)
	private int age;
	private transient String name; // 직렬화 방지
	
	public MyData() {
	}
	public MyData(double height, double weight, int age, String name) {
		this.height = height;
		this.weight = weight;
		this.age = age;
		this.name = name;
	}
	public double getHeight() {
		return height;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "MyData [height=" + height + ", weight=" + weight + ", age=" + age + ", name=" + name + "]";
	}
	
}//class
#2. UseObjectStream Class
1) MyData Class를 활용하여 객체 내보내기/읽기 Stream을 실행하는 class
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * 객체를 직렬화하여 JVM외부로 내보내거나 읽어들이는 클래스
 */
public class UseObjectStream {
	public void writeObj(MyData md) throws IOException, NotSerializableException {
		// 1. 스트림 생성
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(new File("C:/Users/user/Desktop/obj.txt")));
			// 2. 객체 스트림에 기록
			oos.writeObject(md);
			// 3. 스트림의 내용 분출
			oos.flush();
		} finally {
			// 4. 연결 끊기
			if (oos != null) {
				oos.close();
			}//end if
		}//end finally
	}// writeObj
	public MyData readObj() throws IOException, ClassNotFoundException {
		MyData md = null;
		// 1. 스트림 생성
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(new File("C:/Users/user/Desktop/obj.txt")));
			// 2. 스트림에서 객체 읽기
			md = (MyData) ois.readObject(); // method 반환형이 object이므로 클래스로 casting 해줘야 값을 받아올 수 있음
		} finally {
			// 3. 연결 끊기
			if (ois != null) {
				ois.close();
			} // end if
		} // end fianlly
		return md;
	}// readObj
2) main maethod에서 실행해보자!! writeObj를 먼저 실행하면!
	public static void main(String[] args) {
		MyData md = new MyData(180.3, 73.2, 26, "김동동");
		UseObjectStream uos = new UseObjectStream();
		try {
			uos.writeObj(md);
			System.out.println("직렬화된 객체:" + md);
		} catch (NotSerializableException nse) {
			System.out.println("객체가 직렬화되지 않습니다.");
			nse.printStackTrace();
		} catch (IOException ie) {
			System.out.println("객체를 쓰는 동안 문제 발생");
			ie.printStackTrace();
		} // end catch
	}// main
}// class
# 출력 결과 #


- JVM외부로 나간 객체의 내용 & 설정한 경로에 작성된 파일
3) readObj method도 실행해보자!
		try {
			MyData md1 = uos.readObj();
			System.out.println("역직렬화된 객체:" + md1);
		} catch (ClassNotFoundException cnfe) {
			cnfe.printStackTrace();
		} catch (IOException ie) {
			ie.printStackTrace();
		} // end catch
		
	}// main
}// class
# 출력 결과 #

- MyData Class에서 직렬화 방지를 위해 transient로 막아둔 변수는 null로 읽힘
>> 해당 변수는 JVM외부로 나가지 않았다라는 것 확인!
'Java' 카테고리의 다른 글
| [Java] Lambda식 (0) | 2021.09.07 | 
|---|---|
| [Java] charset / early return (0) | 2021.09.06 | 
| [Java] 직렬화(Serializable) / transient / ObjectStream / serialVersionUID (0) | 2021.09.01 | 
| [Java] IO Stream 활용 (2) - 파일 쓰기 (0) | 2021.08.31 | 
| [Java] IO Stream 활용 (1) - 파일 읽기 (0) | 2021.08.30 | 
			  Comments