테스트 사이트 - 개발 중인 베타 버전입니다

자바 입출력 스트림과 파일

cymbal 5년 전 조회 4,088

 

  • 방식1: ArrayList 컬렉션 객체에 저장된 개별 객체 정보를 텍스트 파일(filename)에 저장하고, 파일에 저장된 정보를 읽어와서 ArrayList 컬렉션 객체를 재구성하여 반환함
    • public static void saveDataToFile(ArrayList students, String fileName)
    • public static ArrayList loadDataFromFile(String fileName)
  • 방식2: ObjectOutputStream 객체를 이용하여 ArrayList 객체를 파일(fileName)에 저장하고, ObjectInputStream 객체를 이용하여 파일에 저장된 ArrayList 객체를 읽어옴
    • public static void saveObjectToFile(ArrayList students, String fileName)
    • public static ArrayList loadObjectFromFile(String fileName)

</strong></p>

<p>package hw12;</p>

<p>import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.ArrayList;</p>

<p>public class 실습12 {</p>

<p>    public static void main(String[] args) {

        ArrayList<Student> students = new ArrayList<Student>();

        students.add(new UnderGraduate("100","Lee","사물인터넷",21,"테니스"));

        students.add(new UnderGraduate("101","Kim","지능시스템",21,"요가"));

        students.add(new UnderGraduate("102","Park","사이버보안",24,"댄스"));

        students.add(new UnderGraduate("103","Kim","ICT융합엔터테인먼트",21,"야구"));

        students.add(new Graduate("G100","Jung","정보시스템",26,"석사","인공지능"));

        students.add(new Graduate("G101","Lee","정보시스템",26,"석사","보안"));

        students.add(new Graduate("G200","Han","정보컴퓨터공학",28,"박사","임베디드시스템"));</p>

<p>        saveDataToFile(students, "output.dat");

        System.out.println(loadDataFromFile("output.txt"));</p>

<p>        saveObjectToFile(students, "output.dat");

        System.out.println(loadObjectFromFile("output.dat"));</p>

<p>    }

    public static void saveDataToFile(ArrayList<Student> students, String fileName)  {

     

    }

    public static ArrayList<Student> loadDataFromFile(String fileName) {

     

   

     return null;

    }</p>

<p>    public static void saveObjectToFile(ArrayList<Student> students, String fileName) {

     FileOutputStream fos = null;

  ObjectOutputStream oos = null;</p>

<p>  try {

   fos = new FileOutputStream("object.dat");

  } catch (FileNotFoundException e1) {

   // TODO Auto-generated catch block

   e1.printStackTrace();

  }

  try {

   oos = new ObjectOutputStream(fos);

  } catch (IOException e1) {

   // TODO Auto-generated catch block

   e1.printStackTrace();

  }

try{

   

   // object.dat 파일의 객체 아웃풋스트림을 생성한다.

   fos = new FileOutputStream("object.dat");

   oos = new ObjectOutputStream(fos);

   

   // 해당 파일에 3개의 객체를 순차적으로 쓴다

   oos.writeObject(students);

   

   

   // object.dat 파일에 3개의 객체 쓰기 완료.

   System.out.println("객체를 저장했습니다.");

  

  }catch(Exception e){

   

   e.printStackTrace();

  

  }finally{

   

   // 스트림을 닫아준다.

   if(fos != null) try{fos.close();}catch(IOException e){}

   if(oos != null) try{oos.close();}catch(IOException e){} 

  }</p>

<p> </p>

<p>    }

    public static ArrayList<Student> loadObjectFromFile(String fileName) {

     FileInputStream fis = null;

  ObjectInputStream ois = null;</p>

<p>

try{

   

   // object.dat 파일로 부터 객체를 읽어오는 스트림을 생성한다.

   fis = new FileInputStream("object.dat");

   ois = new ObjectInputStream(fis);

   

   // ObjectInputStream으로 부터 객체 하나씩 읽어서 출력한다.

   // (UserClass) 로 형변환을 작성해야 한다.

   // System.out.println 으로 객체의 구현된 toString() 함수를 호출한다.</p>

<p>

  }catch(Exception e){

   e.printStackTrace();

  }finally{

   

   // 스트림을 닫아준다.

   if(fis != null) try{fis.close();}catch(IOException e){}

   if(ois != null) try{ois.close();}catch(IOException e){}

  }

return null;</p>

<p>      

    }

}</p>

<p>

class Student{

 

 String id;

 String name;

 String dept;

 int age;

 public Student(String id, String name, String dept, int age) {

  super();

  this.id = id;

  this.name = name;

  this.dept = dept;

  this.age = age;

 }

 

 

}</p>

<p>class UnderGraduate extends Student{

 public UnderGraduate(String id, String name, String dept, int age, String circle) {

  super(id, name, dept, age);

  this.circles = circles;

  

 }</p>

<p>

String circles;</p>

<p>public String toString() {

 

 return String.format("%s %s %s %d %s", id, name, dept, age, circles);

 

}

}</p>

<p>

class Graduate extends Student{

  

String degree;

String major;</p>

<p>public Graduate(String id, String name, String dept, int age, String degree, String major) {

 super(id, name, dept, age);

 this.degree = degree;

 this.major = major;

}</p>

<p>public String toString() {

 return String.format("%s %s %s %d %s %s", id, name, dept, age, degree, major);

}

}</p>

<p><strong>

댓글을 작성하려면 로그인이 필요합니다.

답변 1개

이걸 왜 여기서?? ㅋㅋㅋ 혹시 okky 요기 아시나요? 여기가 자바 커뮤니티에요 주언어가 자바라서 여기서 답변 얻어보세요 

로그인 후 평가할 수 있습니다

댓글을 작성하려면 로그인이 필요합니다.

답변을 작성하려면 로그인이 필요합니다.

로그인