기록

*22일차 실습 본문

학원/실습

*22일차 실습

pringspring 2022. 2. 23. 15:14

실습문제4 : 입출력실습문제4_object
 - 패키지 : com.io.test4

1. 객체로 사용할 클래스 : com.io.test4.model.vo.Book.java //직렬화 처리함

* Field
- title:String //도서명
- author:String //저자
- price:int //가격
- dates:Calendar //출판날짜

* Constructor
+ 디폴트 생성자
+ 매개변수 있는 생성자

* Method
+ Setters ans Getters 작성
+ toString():String //Override
: 날짜에 포맷 적용함 ("yyyy'년' MM'월' dd'일 출간')

2. 객체입출력 처리용 클래스 : com.io.test4.controller.BookManager.java
* Field
~ sc:Scanner //초기화 객체 생성함

* default 생성자

* Method
+ fileSave():void
>> 구현내용
1. Book 객체 배열 선언, 5개 초기화함 //샘플데이터 임의 작성
2. "books.dat" 파일에 객체 기록 저장함
3. try with resource 문 사용할 것
4. "books.dat 에 저장 완료!" 출력

+ fileRead():void
>>구현내용
1. Book 객체 배열 선언
2. "books.dat" 파일에서 데이터 읽어서 배열에 저장함
3. 객체 정보를 화면에 출력함
4. try with resource 문 사용할 것
5. "books.dat 읽기 완료!" 출력

3. 테스트용 클래스 : com.io.test4.run.TestBookManager.java
main() 포함
1. BookManager 클래스의 메소드 실행 테스트함

public class TestBookManager {

public static void main(String[] args) {
BookManager manager = new BookManager();
manager.fileSave();
manager.fileRead();
}

}

 

 

package com.io.test4.run;

import com.io.test4.controller.BookManager;

public class TestBookManager {

	public static void main(String[] args) {
		BookManager bm = new BookManager();
		bm.fileSave();
		bm.fileRead();
	}

}
----------------------------------
package com.io.test4.model.vo;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Book implements Serializable {
	
	private static final long serialVersionUID = -8064907533291493923L;
	
	private String title;
	private String author; 
	private int price;
	private Calendar dates;
	
	public Book(){}

	public Book(String title, String author, int price, Calendar dates) {
		super();
		this.title = title;
		this.author = author;
		this.price = price;
		this.dates = dates;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public Calendar getDates() {
		return dates;
	}

	public void setDates(Calendar dates) {
		this.dates = dates;
	}
	
	public String formatCalendar(Calendar cal) {
		Date d = new Date(cal.getTimeInMillis());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 출간");
		return sdf.format(d); 
	}
	
	@Override
	public String toString() {
		return "Book [title=" + title + ", author=" + author 
			 + ", price=" + price + ", dates=" + formatCalendar(dates) + "]";
	}
	
	
	
}
---------------------------------------------
package com.io.test4.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;

import com.io.test4.model.vo.Book;

public class BookManager {
	
	public void fileSave(){
		Book[] bookArr = new Book[5];
		Calendar cal0 = Calendar.getInstance();
		cal0.set(2017, 9, 27);
		bookArr[0] = new Book("신경끄기의 기술", "마크 맨슨", 15000, cal0);
		Calendar cal1 = Calendar.getInstance();
		cal1.set(2016, 7, 19);
		bookArr[1] = new Book("언어의 온도", "이기주", 14000, cal1);
		Calendar cal2 = Calendar.getInstance();
		cal2.set(2017, 11, 5);
		bookArr[2] = new Book("파리의 아파트", "기욤 뮈소", 13000, cal2);
		Calendar cal3 = Calendar.getInstance();
		cal3.set(2012, 11, 19);
		bookArr[3] = new Book("나미야 잡화점의 기적", "히가시노 게이고", 15000, cal3);
//		Calendar cal4 = Calendar.getInstance();
//		cal4.set(2017, 11, 5);
		//[[2]] : 중복된 Calendar 인스턴스를 하나의 메소드화.
		bookArr[4] = new Book("말의 품격", "이기주", 15000, getCalenderInstance(2017, 5, 29));
		
		try (
			FileOutputStream fos = new FileOutputStream("test4/books.dat");
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			ObjectOutputStream oos = new ObjectOutputStream(bos);
				){
			
			oos.writeObject(bookArr);
			System.out.println("books.dat에 저장완료!");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
	


	public Calendar getCalenderInstance(int year, int month, int date) {
		Calendar cal = Calendar.getInstance();
		cal.set(year, month-1, date);
		return cal;
	}



	public void fileRead(){
		Book[] bookArr = null;
		
		try(ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("test4/books.dat")));){
			bookArr = (Book[])ois.readObject();
			for(int i=0; i<bookArr.length; i++){
				if(bookArr[i]!=null)
					System.out.println(bookArr[i].toString());
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
	}
	
	
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'학원 > 실습' 카테고리의 다른 글

*24일차 ncs (수강생 평가) -필기  (0) 2022.02.25
*23일차 실습  (0) 2022.02.24
*21일차 실습  (0) 2022.02.22
*20일차 실습  (0) 2022.02.21
*19일차 실습  (0) 2022.02.17