System.out.println("Hello, World");

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 ObjectStreamTest2 {
	private static String fileName = "D:\\person.obj";//매개변수 받은 객체를 파일로 출력
	public static void writeobject(Object obj){
		//인수로 받은 객체를 person.obj에 출력
		//ObjectOutputStream 이용, 객체를 출력 - 객체 직렬화, 출력 대상 : instance 변수의 값들( attribute)
		
		ObjectOutputStream oos =null;
		try {
			//연결하면서 필터까지 추가한 내용
			oos = new ObjectOutputStream(new FileOutputStream(fileName));
			//쓰기작업시작-writeObject(object)
			oos.writeObject(obj);
			//매개변수로 받은 객체를 넘겨준다.
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(oos!=null)
			{
				try {
					oos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}		
	}

	public static void main(String[] args) {
		PersonDTO p = new PersonDTO("id-111","112312","홍길동",123);
		writeobject(p);//직렬화가 안되서 Exception오류가 나게 된다.		
	}
}



import java.io.Serializable;

public class PersonDTO implements Serializable{
	private String id;
	private String password;
	private String name;
	private int age;
	//생성자, setter, getter tostring
	public PersonDTO(){}
	public PersonDTO(String id, String password, String name, int age) {
		this.id = id;
		this.password = password;
		this.name = name;
		this.age = age;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "PersonDTO [id=" + id + ", password=" + password + ", name="
				+ name + ", age=" + age + "]";
	}
}
Posted by 김마농