ObjectOutputStream을 이용하여 객체를 파일에 저장하기
ObjectOutputStream을 이용하여 객체를 파일에 저장하기
- Student 객체를 저장한다.
- OutjectoutputStream과 ObjectInputStream 사용법을 익힌다.
- 직렬화 객체만 readobject와 writeObject를 사용하여 읽고 저장할 수 있다.
import java.io.*;import java.util.Vector;public class ObjectStudentWrite { public int write(String fname, Vector v) throws IOException{ //public int write(String fname, Vector int objectNumber=0; try { FileOutputStream fos=new FileOutputStream(fname); ObjectOutputStream oos=new ObjectOutputStream(fos);//throws objectNumber=v.size(); oos.writeInt(objectNumber); System.out.println(objectNumber+"개의 Student가 입력됨"); for(int i=0;i oos.writeInt(i); oos.writeObject((Student)v.get(i)); //oos.writeObject(v.get(i));//JAVA5 oos.flush(); System.out.println(i+"번째의 Student가 입력됨"); } oos.close(); fos.close(); } catch (FileNotFoundException e) { System.out.println("잘못된 파일이름을 입력했습니다."); } catch(Exception ee){ throw new IOException("타입이 이상합니다."+ee); } return objectNumber; } public void read(String fname) throws IOException{ try { FileInputStream fis = new FileInputStream(fname); ObjectInputStream ois=new ObjectInputStream(fis);//throws int objectNumber=ois.readInt(); System.out.println(objectNumber+"개의 Student를 읽음"); for(int i=0;i try { System.out.print(ois.readInt()+"번째 :"); System.out.println((Student)ois.readObject()); } catch (ClassNotFoundException e1) { System.out.println("잘못된 타입입니다.."); } } ois.close(); fis.close(); } catch (FileNotFoundException e) { System.out.println("잘못된 파일이름을 입력했습니다."); } }} |
import java.io.IOException;import java.util.Vector;public class ObjectStudentWriteMain { public static void main(String[] args) { ObjectStudentWrite osw=new ObjectStudentWrite(); Vector v=new Vector(5, 5); //Vector v.add(new Student("홍길동",17,"한양")); v.add(new Student("홍길순",15,"순천")); v.add(new Student("몽룡",20,"화천")); v.add(new Student("춘향",18,"삼척")); try { osw.write("stu.txt",v); osw.read("stu.txt"); } catch (IOException e) { e.printStackTrace(); } }} |
댓글
댓글 쓰기