-아래와 같은 Phone 클래스를 입출력하고자 함.
-객체를 입출력할때에는 implements Serializable -> 직렬화과정 필수
package com.br.chap04_assist.part02_object.model.vo;
import java.io.Serializable;
public class Phone implements Serializable{ // 직렬화
//객체 자체를 입출력 하고자 한다면 반드시 직렬화과정 필수
private String name;
private int price;
//기본생성자, 매개변수 생성자, getter/setter / toString
//단축키 alt+Shift+s
public Phone() {}
//매개변수 생성자 단축키 alt+Shift+s => o
public Phone(String name, int price) {
super();
this.name = name;
this.price = price;
}
//getter/setter 단축키 alt+shift+s => r (getter/setter창) => alt+a(모든필드 체크) => alt+r(generate)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
//toString 단축기 alt+shift + s => s(toString창) => enter
@Override
public String toString() {
return "Phone [name=" + name + ", price=" + price + "]";
}
}
1. 프로그램 --> 파일(출력)
//FileOutputStream : 파일과 연결해서 1byte단위로 출력할 수있는 기반 스트림
//ObjectOutputStream : 객체 단위로 출력할 수 있도록 도움을 주는 보조스트림(ObjectWriter없음)
public void fileSave() {
//출력시킬 데이터 (Phone 객체)
Phone ph = new Phone("아이폰",1300000);
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d_phone.txt"))){
oos.writeObject(ph);
//NotSerializableException : 직렬화가 되어있지않아 발생하는 예외 (스트림 통과하기위해 객체 직렬화)->객체명 implements Serializable
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2. 프로그램 <---파일(입력)
//FileInputStream 기반스트림
// ObjectInputStrea 보조스트림
public void fileRead() {
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d_phone.txt"))){
//readObject
Phone ph = (Phone)ois.readObject(); // 부모클래스-> 자식클래스로 형변환
System.out.println(ph);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
'JAVA' 카테고리의 다른 글
13_ Collection _Collection과 List_ArrayList (0) | 2022.11.08 |
---|---|
12. IO (IntputOutput) _객체 배열 입출력 (0) | 2022.11.08 |
12. IO (IntputOutput)_ Stream _ 보조스트림 (0) | 2022.11.08 |
12. IO (IntputOutput) _문자기반 Stream (0) | 2022.11.08 |
12. IO (IntputOutput) _바이트기반Stream (0) | 2022.11.07 |