삼성SDS_멀티캠퍼스/Java

18일 차 객체를 입출력 하려면 직렬화를 해야한다.

박성우기 2015. 10. 2. 09:42
반응형

import java.io.Serializable;


public class Car implements Serializable{

private static final long serialVersionUID = -5794225376776071193L;

private String color;

private int speed;

private int mileage;


public String getColor() {

return color;

}


public void setColor(String color) {

this.color = color;

}


public int getSpeed() {

return speed;

}


public void setSpeed(int speed) {

this.speed = speed;

}


public int getMileage() {

return mileage;

}


public void setMileage(int mileage) {

this.mileage = mileage;

}


@Override

public String toString() {

return "Car [color=" + color + ", speed=" + speed + ", mileage=" + mileage + "]";

}


}




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 Test2 {
public static void main(String[] args) {

// 최종적으로 사용할 스트림 참조변수를 미리선언
// try구문에서 사용하고 finally블럭에서 닫기 위해서
ObjectInputStream in = null;
ObjectOutputStream out = null;

// FileoutputStream에 직접 ObjectOutputStream을 연결했다
// 중간에 BufferdoutputStream 넣어도 상관없다
try {
out = new ObjectOutputStream(new FileOutputStream("data.bin"));
Car c = new Car();
c.setColor("blue");
c.setSpeed(100);
c.setMileage(5000);
out.writeObject(c);
out.flush();
in = new ObjectInputStream(new FileInputStream("data.bin"));
Car myCar = (Car) in.readObject();
System.out.println(myCar);
} catch (FileNotFoundException e) {
System.out.println("파일이 존재하지 않습니다");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("입출력에 문제가 생겼습니다");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("클래스가 존재하지 않습니다");
} finally {

try {
if (out != null)
out.close();
if (in != null)
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
}













객체를 InputStream, outputStream 하려면 Serializable을 선언해야 한다.


반응형