IT/Programming / / 2023. 4. 20. 13:04

[JAVA] 객체를 파일로 저장 및 출력 사용 예제

반응형
package dayday19;

import java.io.*;

class Pokemon implements Serializable{
	private static final long serialVersionUID = 1L;
	//The serializable class Pokemon
	//does not declare a static final
	//serialVersionUID field of type long
	//파일의 버전이 바뀌었다.. 표시용으로 사용
	String name;
	int lv, hp;
	
	Pokemon(String name, int lv, int hp){
		this.name = name;
		this.lv = lv;
		this.hp = hp;		
	}
	@Override
	public String toString(){
		return "이름 : " + name + "Lv : " + lv + "/HP : " + hp;		
	}
	
}

public class test01 {
	public static void main(String[] args) {
		//"피카츄"객체를 pokemon.pok에 저장
		Pokemon p = new Pokemon("피카츄",1,100);
		
		try {
			/////////////////////////저장//////////////////////////
			//주 스트림 생성
			FileOutputStream fos = new FileOutputStream("pokemon.pok");
			
			//보조 스트림 생성 후 주 스트림과 연결
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			
			//객체 p를 스트림에 보내어 쓰기
			oos.writeObject(p);
			//여러 객체를 보내어 쓰기
			oos.writeObject(new Pokemon("라이츄",2,200));;
			oos.writeObject(new Pokemon("꼬북이",3,300));;
			
			
			
			//스트림 제거
			oos.close();
			fos.close();
			
			
			

			/////////////////////////읽기//////////////////////////
			//주 스트림 생성
			FileInputStream fis = new FileInputStream("pokemon.pok");
			
			//보조 스트림 생성 후 주 스트림과 연결
			ObjectInputStream ois = new ObjectInputStream(fis);
			
			//casting하여 p1에 입력
			//Pokemon p1 = (Pokemon)ois.readObject();
			
			while(true){
				try{
					Pokemon pp = (Pokemon)ois.readObject();
					System.out.println(pp);
					
				} catch(EOFException e){
					break;
				}
			}//exception을 다 외워야 예외처리를 할 수 있나?
			
			
			/*
			System.out.println(p1);
			System.out.println(ois.readObject());
			System.out.println(ois.readObject());
			*/
			/*
			 * 이름 : 피카츄Lv : 1/HP : 100
			 * 이름 : 라이츄Lv : 2/HP : 200
			 * 이름 : 꼬북이Lv : 3/HP : 300
			 */
			//ObjectInputStream에는 hasNext가 없다. -> Try Catch를 사용하여 해결
			

			//System.out.println(ois.readObject());
			//EOFException
			
				
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유