Published 2020. 5. 5. 23:18
728x90
반응형

IO와 List를 활용한 예제

 

ArrayList에 3개의 Book객체를 생성하여 저장하고, books.dat 파일에 객체를 기록한 후 저장

books.dat에 기록된 객체 정보를 읽어서 각각의 정보와 할인된 가격을 출력

 

> 실행결과

총 균 쇠, 재레드 다이아몬드, 문학사상, 28000원, 10% 할인 
할인된 가격 : 25200원
페스트, 알베르 카뮈, 민음사, 13000원, 10% 할인 
할인된 가격 : 11700원
팩트풀니스, 한스 로슬링, 김영사, 19800원, 10% 할인 
할인된 가격 : 17820원

 

public class BookListTest {

	public static void main(String[] args) {
		BookListTest test5 = new BookListTest();
		List<Book> list = new ArrayList<>();
		
		test5.storeList(list);
		test5.saveFile(list);
		List<Book> booksList = test5.loadFile();
		test5.printList(booksList);
	}
	
	public void storeList(List<Book> list) {
		list.add(new Book("총 균 쇠", "재레드 다이아몬드", "문학사상", 28000, 0.1));
		list.add(new Book("페스트", "알베르 카뮈", "민음사", 13000, 0.1));
		list.add(new Book("팩트풀니스", "한스 로슬링", "김영사", 19800, 0.1));
	}
	
	public void saveFile(List<Book> list) {
		try(ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("books.dat")));) {
			oos.writeObject(list);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public List<Book> loadFile() {
		List<Book> list = new ArrayList<>();
		try(ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("books.dat")));) {
			list = (ArrayList<Book>) ois.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();	
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	public void printList(List<Book> list) {
		for(Book b : list) {
			System.out.println(b);
		}
	}
}
public class Book implements Serializable{
	private static final long serialVersionUID = 1L;
	
	private String title;
	private String author;
	private String publisher;
	private int price;
	private double discountRate;
	
	public Book() {}

	public Book(String title, String author, String publisher, int price, double discountRate) {
		this.title = title;
		this.author = author;
		this.publisher = publisher;
		this.price = price;
		this.discountRate = discountRate;
	}

	@Override
	public String toString() {
		return  String.format("%s, %s, %s, %d원, %.0f%% 할인 %n할인된 가격 : %d원", 
								title, author, publisher, price, discountRate*100, getDiscountPrice());
	}

	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 String getPublisher() {return publisher;}
	public void setPublisher(String publisher) {this.publisher = publisher;}
	public int getPrice() {return price;}
	public void setPrice(int price) {this.price = price;}
	public double getDiscountRate() {return discountRate;}
	public void setDiscountRate(double discountRate) {this.discountRate = discountRate;}
	public int getDiscountPrice() {return (int)(price*(1-discountRate));}
}
반응형
복사했습니다!