By GokiSoft.com| 15:33 12/07/2023|
Java Advanced

Bài tập quản lý sách & lưu thông tin trên Files BT1091

Tạo một lớp đối tượng book gồm các thuộc tính : tên sách, tác giả, giá bán, ngày xuất bản, nhà sản xuất.

- Viết hàm tạo và getter/setter

- Viết hàm nhập và hàm hiển thị

Trong lớp Main tạo một List<Book> bookList -> để quản lý sách nhập vào

Xây dựng menu trương trình như sau

1. Nhập thông tin N quấn sách

2. Hiển thị thông tin sách

3. Sắp xếp theo tên tác giả

4. Lưu thông tin mỗi quyển sách vào file data.txt theo định dạng (ten sách, tác giả, giá bán, ngày xuất bản, nhà xuất bản) mỗi quyển sách trên một dòng

Ví dụ :

lap trinh c, quách tuấn ngọc, 20000, 06-06-1999, Kim Đồng

lap trinh PHP, quách tuấn ngọc, 20000, 06-06-1999, Kim Đồng

5. Đọc dữ liệu từ file data.txt và hiển thị ra màn hình

6. Thoát

Liên kết rút gọn:

https://gokisoft.com/1091

Bình luận

avatar
GokiSoft.com [Teacher]
2021-09-09 02:21:59


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson04.bt1091;

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.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    static List<Book> bookList;
    static Scanner scan;
    
    public static void main(String[] args) {
        bookList = new ArrayList<>();
        scan = new Scanner(System.in);
        
        int choose;
        
        do {
            showMenu();
            choose = Integer.parseInt(scan.nextLine());
            
            switch(choose) {
                case 1:
                    input();
                    break;
                case 2:
                    display();
                    break;
                case 3:
                    sortByAuthorName();
                    display();
                    break;
                case 4:
                    saveObjectFile();
                    break;
                case 5:
                    saveTextFile();
                    break;
                case 6:
                    readObjectFile();
                    break;
                case 7:
                    System.out.println("Thoat!!!");
                    break;
                default:
                    System.out.println("Nhap sai!!!");
                    break;
            }
        } while(choose != 7);
    }
    
    static void showMenu() {
        System.out.println("1. Nhap N quyen sach");
        System.out.println("2. Hien thi thong tin");
        System.out.println("3. Sap xep theo ten tac gia (A-Z)");
        System.out.println("4. Luu data.obj");
        System.out.println("5. Luu data.txt");
        System.out.println("6. Doc du lieu data.obj");
        System.out.println("7. Thoat");
        System.out.println("Chon: ");
    }

    private static void input() {
        System.out.println("Nhap so sach can them N = ");
        int N = Integer.parseInt(scan.nextLine());
        
        for (int i = 0; i < N; i++) {
            Book b = new Book();
            b.input();
            
            bookList.add(b);
        }
    }

    private static void display() {
        System.out.println("+++ Hien thi thong tin sach");
        bookList.forEach(book -> {
            book.display();
        });
    }

    private static void sortByAuthorName() {
        Collections.sort(bookList, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                return o1.getAuthorName().compareToIgnoreCase(o2.getAuthorName());
            }
        });
    }

    private static void saveObjectFile() {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        try {
            fos = new FileOutputStream("data.obj");
            oos = new ObjectOutputStream(fos);
            
            oos.writeObject(bookList);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private static void saveTextFile() {
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream("data.txt");
            
            for (Book book : bookList) {
                String line = book.getFileLine();
                byte[] data = line.getBytes("utf8");
                
                fos.write(data);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private static void readObjectFile() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            fis = new FileInputStream("data.obj");
            ois = new ObjectInputStream(fis);
            
            List<Book> dataList = (List<Book>) ois.readObject();
            
            dataList.forEach(book -> {
                bookList.add(book);
            });
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


#Book.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lesson04.bt1091;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Book implements Serializable{
    String bookName, authorName, publishDate, manufacturerName;
    int price;

    public Book() {
    }

    public Book(String bookName, String authorName, String publishDate, String manufacturerName, int price) {
        this.bookName = bookName;
        this.authorName = authorName;
        this.publishDate = publishDate;
        this.manufacturerName = manufacturerName;
        this.price = price;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public String getPublishDate() {
        return publishDate;
    }

    public void setPublishDate(String publishDate) {
        this.publishDate = publishDate;
    }

    public String getManufacturerName() {
        return manufacturerName;
    }

    public void setManufacturerName(String manufacturerName) {
        this.manufacturerName = manufacturerName;
    }

    public int getPrice() {
        return price;
    }

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

    public String getFileLine() {
        return bookName + "," + authorName + "," + price + "," + publishDate + "," + manufacturerName + "\n";
    }
    
    @Override
    public String toString() {
        return "bookName=" + bookName + ", authorName=" + authorName + ", publishDate=" + publishDate + ", manufacturerName=" + manufacturerName + ", price=" + price;
    }
    
    public void display() {
        System.out.println(this);
    }
    
    public void input() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Nhap ten sach: ");
        bookName = scan.nextLine();
        
        System.out.println("Nhap ten tac gia: ");
        authorName = scan.nextLine();
        
        System.out.println("Ngay xuat ban (dd/MM/yyyy): ");
        publishDate = scan.nextLine();
        
        System.out.println("Nhap nha san xuat: ");
        manufacturerName = scan.nextLine();
        
        System.out.println("Nhap gia: ");
        price = Integer.parseInt(scan.nextLine());
    }
}


avatar
Hieu Ngo [community,C2009G]
2021-09-07 04:14:45


#Book.java


import java.io.Serializable;
import java.util.Scanner;

public class Book implements Serializable {
    private String nameBook, author, producer, mfgDate;
    private float price;

    public Book() {
    }

    public Book(String nameBook, String author, String producer, String mfgDate, float price) {
        this.nameBook = nameBook;
        this.author = author;
        this.producer = producer;
        this.mfgDate = mfgDate;
        this.price = price;
    }

    public String getNameBook() {
        return nameBook;
    }

    public Scanner getScanner() {
        return new Scanner(System.in);
    }

    public void setNameBook(String nameBook) {
        this.nameBook = nameBook;
    }

    public String getAuthor() {
        return author;
    }

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

    public String getProducer() {
        return producer;
    }

    public void setProducer(String producer) {
        this.producer = producer;
    }

    public String getMfgDate() {
        return mfgDate;
    }

    public void setMfgDate(String mfgDate) {
        this.mfgDate = mfgDate;
    }

    public float getPrice() {
        return price;
    }

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

    public void input() {
        System.out.println("Enter name of book:");
        this.nameBook = getScanner().nextLine();
        System.out.println("Enter author:");
        this.author = getScanner().nextLine();
        System.out.println("Enter price");
        this.price = getScanner().nextFloat();
        System.out.println("Enter Manufacturing Date");
        this.mfgDate = getScanner().nextLine();
        System.out.println("Enter producer");
        this.producer = getScanner().nextLine();
    }

    @Override
    public String toString() {
        return
                nameBook + '\'' +
                author + '\'' +
                price + '\'' +
                mfgDate + '\'' +
                producer;
    }
}


#Main.java


import javax.annotation.processing.SupportedSourceVersion;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.DeflaterInputStream;
import java.util.zip.ZipOutputStream;

public class Main {
    public static void main(String [] args){
        List<Book> bookList  = new ArrayList<>();
        int x;
        do {
            System.out.println("1. Nhập thông tin N quấn sách");
            System.out.println("2. Hiển thị thông tin sách");
            System.out.println("3. Sắp xếp theo tên tác giả");
            System.out.println("4. Lưu thông tin sách vào file data.obj");
            System.out.println("5. Lưu thông tin mỗi quyển sách vào file data.txt");
            System.out.println("6. Nén file data.txt thành file data.dfl");
            System.out.println("7. Đọc dữ liệu từ file data.obj và hiển thị ra màn hình");
            System.out.println("8. Thoát");
            System.out.println("Your choice:");
            x = (new Scanner(System.in)).nextInt();
            switch (x) {
                case 1: {
                    System.out.println("Enter n:");
                    int n = (new Scanner(System.in)).nextInt();

                    for (int i = 0; i < n; i++) {
                        Book book = new Book();
                        book.input();
                        bookList.add(book);
                    }
                    break;
                }
                case 2: {
                    for (Book book : bookList) {
                        System.out.println(book.toString());
                    }
                    break;
                }
                case 3: {
                    Collections.sort(bookList, new Comparator<Book>() {
                        @Override
                        public int compare(Book o1, Book o2) {
                            return o1.getAuthor().compareToIgnoreCase(o2.getAuthor());
                        }
                    });
                    for (Book book : bookList) {
                        System.out.println(book);
                    }
                    break;
                }
                case 4: {
                    FileOutputStream fos = null;
                    ObjectOutputStream oos = null;

                    try {
                        fos = new FileOutputStream("data.obj");
                        oos = new ObjectOutputStream(fos);
                        oos.writeObject(bookList);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (oos != null) {
                            try {
                                oos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                }
                case 5: {
                    FileOutputStream fos = null;
                    try {
                         fos = new FileOutputStream("data.txt");
                        for(Book book : bookList) {
                            String line = book.toString() + "\n";
                            byte[] data = line.getBytes(StandardCharsets.UTF_8);
                            fos.write(data);
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if(fos != null) {
                           try {
                               fos.close();
                           } catch (IOException e) {
                               e.printStackTrace();
                           }
                        }
                    }
                    break;

                }
                case 6: {
                    FileInputStream fis = null;
                    FileOutputStream fos = null;
                    DeflaterInputStream dis = null;

                    try {
                        fis = new FileInputStream("data.txt");
                        dis = new DeflaterInputStream(fis);
                        fos = new FileOutputStream("data.dfl");

                        int a;
                        while ((a = dis.read()) != -1) {
                            fos.write(a);
                        }

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (dis != null) {
                            try {
                                dis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                }
                case 7: {
                    FileInputStream fis = null;
                    ObjectInputStream ois = null;
                    try {
                        fis = new FileInputStream("data.obj");
                        ois = new ObjectInputStream(fis);
                        bookList = (List<Book>) ois.readObject();
                        for(Book book : bookList) {
                            System.out.println(book.toString());
                        }

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        if(fis!=null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if(ois!=null) {
                            try {
                                ois.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                    break;
                }
                case 8: {
                    return;
                }
            }


        }while(x>=1 && x<=8);
    }
}



avatar
GokiSoft.com [Teacher]
2021-08-16 02:25:57


#Utility.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03.bt1091;

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Utility {
    public static int scanInt(Scanner scan) {
        int value;
        while(true) {
            try {
                value = Integer.parseInt(scan.nextLine());
                break;
            } catch(NumberFormatException e) {
                System.out.println("Nhap lai: ");
            }
        }
        return value;
    }
}


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03.bt1091;

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int choose;
        
        do {
            showMenu();
            choose = Utility.scanInt(scan);
            
            switch(choose) {
                case 1:
                    DataController.getInstance().input();
                    break;
                case 2:
                    DataController.getInstance().display();
                    break;
                case 3:
                    DataController.getInstance().sortByAuthorName();
                    DataController.getInstance().display();
                    break;
                case 4:
                    DataController.getInstance().saveBinaryFile();
                    break;
                case 5:
                    DataController.getInstance().saveTextFile();
                    break;
                case 6:
                    DataController.getInstance().zipFile();
                    break;
                case 7:
                    DataController.getInstance().readBinaryFile();
                    DataController.getInstance().display();
                    break;
                case 8:
                    System.out.println("Thoat!!!");
                    break;
                default:
                    System.out.println("Nhap sai!");
                    break;
            }
        } while(choose != 8);
    }
    
    static void showMenu() {
        System.out.println("1. Nhap N sach");
        System.out.println("2. Hien thi");
        System.out.println("3. Sap xep theo tac gia");
        System.out.println("4. Luu thong tin data.obj");
        System.out.println("5. Luu thong tin data.txt");
        System.out.println("6. Nen file data.txt thanh data.dfl");
        System.out.println("7. Doc du lieu tu data.obj va hien thi");
        System.out.println("8. Thoat");
        System.out.println("Chon: ");
    }
}


#DataController.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03.bt1091;

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.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Singleton
 * @author Diep.Tran
 */
public class DataController {
    List<Book> bookList;
    
    private static DataController instance = null;
    
    private DataController() {
        bookList = new ArrayList<>();
    }
    
    public static DataController getInstance() {
        if(instance == null) {
            instance = new DataController();
        }
        return instance;
    }
    
    public void input() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Nhap so sach can them: ");
        int N = Utility.scanInt(scan);
        
        for (int i = 0; i < N; i++) {
            Book book = new Book();
            book.input();
            
            bookList.add(book);
        }
    }
    
    public void display() {
        System.out.println("Thong tin sach: ");
        
        bookList.forEach(book -> {
            book.display();
        });
    }
    
    public void sortByAuthorName() {
        Collections.sort(bookList, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                return o1.getAuthorName().compareToIgnoreCase(o2.getAuthorName());
            }
        });
    }
    
    public void saveBinaryFile() {
        //Thiet lap trang thai luu file.
        Scanner scan = new Scanner(System.in);
        System.out.println("Lua chon cach ghi");
        System.out.println("1. Luu moi");
        System.out.println("2. Ghi bo sung");
        System.out.println("Chon: ");
        int choose = Utility.scanInt(scan);
        
        boolean status = true;
        
        if(choose == 1) {
            status = false;
        }
        
        //Thuc hien luu file
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        try {
            fos = new FileOutputStream("data.obj", status);
            oos = new ObjectOutputStream(fos);
            
            //oos.writeObject(bookList);//Luu theo List -> doc theo List
            for (Book book : bookList) {
                oos.writeObject(book);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public void saveTextFile() {
        //Thiet lap trang thai luu file.
        Scanner scan = new Scanner(System.in);
        System.out.println("Lua chon cach ghi");
        System.out.println("1. Luu moi");
        System.out.println("2. Ghi bo sung");
        System.out.println("Chon: ");
        int choose = Utility.scanInt(scan);
        
        boolean status = true;
        
        if(choose == 1) {
            status = false;
        }
        
        //Thuc hien luu file
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream("data.txt", status);
            
            for (Book book : bookList) {
                String line = book.getFileLine();
                
                byte[] data = line.getBytes("utf8");
                
                fos.write(data);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public void zipFile() {
        
    }
    
    public void readBinaryFile() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            fis = new FileInputStream("data.obj");
            ois = new ObjectInputStream(fis);
            
            while(true) {
                Book book = null;
                try {
                    book = (Book) ois.readObject();
                } catch(Exception e) {
                    break;
                }
                
                bookList.add(book);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


#Book.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03.bt1091;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Book implements Serializable{
    String name, authorName, nxb, manufacturerName;
    int price;

    public Book() {
    }

    public Book(String name, String authorName, String nxb, String manufacturerName, int price) {
        this.name = name;
        this.authorName = authorName;
        this.nxb = nxb;
        this.manufacturerName = manufacturerName;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public String getNxb() {
        return nxb;
    }

    public void setNxb(String nxb) {
        this.nxb = nxb;
    }

    public String getManufacturerName() {
        return manufacturerName;
    }

    public void setManufacturerName(String manufacturerName) {
        this.manufacturerName = manufacturerName;
    }

    public int getPrice() {
        return price;
    }

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

    @Override
    public String toString() {
        return "Book{" + "name=" + name + ", authorName=" + authorName + ", nxb=" + nxb + ", manufacturerName=" + manufacturerName + ", price=" + price + '}';
    }
    
    public String getFileLine() {
        return name + ", " + authorName + ", " + price + ", " + nxb + ", " + manufacturerName + "\n";
    }
    
    public void display() {
        System.out.println(this);
    }
    
    public void input() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Nhap ten: ");
        name = scan.nextLine();
        
        System.out.println("Nhap tac gia: ");
        authorName = scan.nextLine();
        
        System.out.println("Nhap ngay xuat ban: ");
        nxb = scan.nextLine();
        
        System.out.println("Nhap ten nha san xuat: ");
        manufacturerName = scan.nextLine();
        
        System.out.println("Nhap gia tien: ");
        price = Utility.scanInt(scan);
    }
}


avatar
Nguyễn Tiến Đạt [T2008A]
2021-03-16 15:43:45


#Book.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Java2.lesson3.QuanLiSachBangFile;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author MyPC
 */
public class Book implements Serializable{
    String bookName, authorName;
    int price;
    String datePublishing;
    String manu;

    public Book() {
    }

    public Book(String bookName, String authorName, int price, String datePublishing, String manu) {
        this.bookName = bookName;
        this.authorName = authorName;
        this.price = price;
        this.datePublishing = datePublishing;
        this.manu = manu;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public int getPrice() {
        return price;
    }

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

    public String getDatePublishing() {
        return datePublishing;
    }

    public void setDatePublishing(String datePublishing) {
        this.datePublishing = datePublishing;
    }

    public String getManu() {
        return manu;
    }

    public void setManu(String manu) {
        this.manu = manu;
    }
    public void input(){
        Scanner scan = new Scanner(System.in);
        System.out.println("Nhap ten sach:");
        bookName = scan.nextLine();
        System.out.println("Nhap ten tac gia:");
        authorName = scan.nextLine();
        System.out.println("Gia ban:");
        price = Integer.parseInt(scan.nextLine());
        System.out.println("Ngay xuat ban:");
        datePublishing = scan.nextLine();
        System.out.println("Nha san xuat:");
        manu = scan.nextLine();
    }
    
    public void display(){
        System.out.println(this);
    }

    @Override
    public String toString() {
        return "Book{" + "bookName=" + bookName + ", authorName=" + authorName + ", price=" + price + ", datePublishing=" + datePublishing + ", manu=" + manu + '}';
    }
    
    public String getLine(){
        return bookName + ", " + authorName + ", " + price + ", " + datePublishing + ", " + manu + "\n";
    }
}


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Java2.lesson3.QuanLiSachBangFile;

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.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DeflaterInputStream;

/**
 *
 * @author MyPC
 */
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        List<Book> bookList = new ArrayList<>();
        int choose;
        do{
            showMenu();
            System.out.println("Lua chon chuong trinh:");
            choose = Integer.parseInt(scan.nextLine());
            switch(choose){
                case 1:
                    int n;
                    System.out.println("Nhap so luong quyen sach muon nhap:");
                    n = Integer.parseInt(scan.nextLine());
                    for (int i = 0; i < n; i++) {
                        Book book = new Book();
                        book.input();
                        bookList.add(book);
                    }
                    break;
                case 2:
                    bookList.forEach((book) -> {
                        book.display();
                    });
                    break;
                case 3:
                    Collections.sort(bookList, (Book o1, Book o2) -> o1.authorName.compareToIgnoreCase(o2.authorName));                         
                    break;
                case 4:
                    saveObj(bookList);
                    break;
                case 5:
                    saveTxt(bookList);
                    break;
                case 6:
                    deflaterFile();
                    break;
                case 7:
                    readObj();
                    break;
                case 8:
                    System.out.println("Tam biet!!");
                    break;
                default:
                    System.out.println("Nhap sai!!");
                    break;
            }
        }while(choose != 8);
    }
    
    static void showMenu(){
        System.out.println("1.Nhap thong tin N quyen sach");
        System.out.println("2.Hien thi thong tin N quyen sach");
        System.out.println("3.Sap xep theo ten tac gia");
        System.out.println("4.Luu thong tin vao file data.obj");
        System.out.println("5.Luu thong tin vao file data.txt");
        System.out.println("6.Nen file data.txt thanh file data.dfl");
        System.out.println("7.Doc du lieu tu file data.obj");
        System.out.println("8.Thoat");
    }

    private static void saveObj(List<Book> bookList) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream("data.obj");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(bookList);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                oos.close();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Save thanh cong!!");
        }
    }

    private static void saveTxt(List<Book> bookList) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("data.txt");
            for (Book book : bookList) {
                byte[] b = book.getLine().getBytes();
                fos.write(b);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Save thanh cong!!");
        }
    }

    private static void readObj() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        List<Book>abcd = new ArrayList<>();
        try {
            fis = new FileInputStream("data.obj");
            ois = new ObjectInputStream(fis);
            abcd = (List<Book>) ois.readObject();
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                ois.close();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        for (Book book : abcd) {
            System.out.println(book);
        }
    }
    
    public static void deflaterFile(){
        FileInputStream fis = null;
        DeflaterInputStream dis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("data.obj");
            dis = new DeflaterInputStream(fis);

            fos = new FileOutputStream("data.dfl");

            int code;
            while ((code = dis.read()) != -1) {
                fos.write(code);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis != null) {
                try {
                    fis.close();

                } catch (IOException ex) {
                    Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (dis != null) {
                try {
                    dis.close();

                } catch (IOException ex) {
                    Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (fos != null) {
                try {
                    fos.close();

                } catch (IOException ex) {
                    Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


avatar
hoangkhiem [C1907L]
2020-05-07 20:59:09



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Java2b4;

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.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Admin
 */
public class Main {

    public static void main(String[] args) {
        Scanner ip = new Scanner(System.in);
        List<Book> bookList = new ArrayList<>();
        int chon, n;
        do {
            menu();
            chon = Integer.parseInt(ip.nextLine());
            switch (chon) {
                case 1:
                    System.out.println("Nhập số cuốn sách cần nhập  : ");
                    n = Integer.parseInt(ip.nextLine());
                    for (int i = 0; i < n; i++) {
                        Book book = new Book();
                        book.nhap();
                        bookList.add(book);
                    }
                    break;
                case 2:
                    for (int i = 0; i < bookList.size(); i++) {
                        bookList.get(i).hienthi();
                    }
                    break;
                case 3:
                    Collections.sort(bookList, (Book o1, Book o2) -> o1.getTacgia().compareToIgnoreCase(o2.getTacgia()));
                    break;
                case 4:
                    svfileobj((ArrayList<Book>) bookList);
                    break;
                case 5:

                    break;
                case 6:

                    break;
                case 7:
                    readFile();
                    break;
                case 8:
                default:
                    break;

            }
        } while (chon != 9);
    }

    static void menu() {
        System.out.println("1. Nhập thông tin N quấn sách");
        System.out.println("2. Hiển thị thông tin sách");
        System.out.println("3. Sắp xếp theo tên tác giả");
        System.out.println("4. Lưu thông tin sách vào file data.obj");
        System.out.println("5. Lưu thông tin mỗi quyển sách vào file data.txt theo định dạng (ten sách, tác giả, giá bán, ngày xuất bản, nhà xuất bản) mỗi quyển sách trên một dòng");
        System.out.println("6. Nén file data.txt thành file data.dfl");
        System.out.println("7. Đọc dữ liệu từ file data.obj và hiển thị ra màn hình");
        System.out.println("8. Thoát");
    }

    private static void svfileobj(ArrayList<Book> bookList) {
    FileOutputStream fos = null;
    ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream("data.obj");
              oos = new ObjectOutputStream(fos);
              oos.writeObject(bookList);
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            System.err.println("Lỗi ghi file :  " +ex);
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(oos != null){
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private static void readFile() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream("data.obj");
            ois = new ObjectInputStream(fis);
            ArrayList<Book> bookList = (ArrayList<Book>) ois.readObject();

            for (Book object : bookList) {
                object.hienthi();
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Java2b4;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author Admin
 */
public class Book implements Serializable {
    String tensach,tacgia,giaban,ngaysanxuat,nhasanxuat;

    public Book() {
    }

    public Book(String tensach, String tacgia, String giaban, String ngaysanxuat, String nhasanxuat) {
        this.tensach = tensach;
        this.tacgia = tacgia;
        this.giaban = giaban;
        this.ngaysanxuat = ngaysanxuat;
        this.nhasanxuat = nhasanxuat;
    }

    public String getTensach() {
        return tensach;
    }

    public void setTensach(String tensach) {
        this.tensach = tensach;
    }

    public String getTacgia() {
        return tacgia;
    }

    public void setTacgia(String tacgia) {
        this.tacgia = tacgia;
    }

    public String getGiaban() {
        return giaban;
    }

    public void setGiaban(String giaban) {
        this.giaban = giaban;
    }

    public String getNgaysanxuat() {
        return ngaysanxuat;
    }

    public void setNgaysanxuat(String ngaysanxuat) {
        this.ngaysanxuat = ngaysanxuat;
    }

    public String getNhasanxuat() {
        return nhasanxuat;
    }

    public void setNhasanxuat(String nhasanxuat) {
        this.nhasanxuat = nhasanxuat;
    }
    public void nhap(){
        Scanner ip = new Scanner(System.in);
        System.out.println("Mời bạn nhập tên sách : ");
        tensach = ip.nextLine();
        System.out.println("Mời bạn nhập tác giả : ");
        tacgia = ip.nextLine();
        System.out.println("Mời bạn nhập giá bán : ");
        giaban = ip.nextLine();
        System.out.println("Mời bạn nhập ngày sản xuất : ");
        ngaysanxuat = ip.nextLine();
        System.out.println("Mời bạn nhập nhà sản xuất :");
        nhasanxuat = ip.nextLine();
    }
    public void hienthi(){
        System.out.println(toString());
    }

    @Override
    public String toString() {
        return  "tensach=" + tensach + ", tacgia=" + tacgia + ", giaban=" + giaban + ", ngaysanxuat=" + ngaysanxuat + ", nhasanxuat=" + nhasanxuat ;
    }
   
}


avatar
Hoàng Quang Huy [C1907L]
2020-05-04 12:09:28




package lesson4;

import java.util.Scanner;

public class Book {
    private String name,author,publish_date,publisher;
    private double price;

    public Book() {
    }

    public Book(String name, String author, String publish_date, String publisher, double price) {
        this.name = name;
        this.author = author;
        this.publish_date = publish_date;
        this.publisher = publisher;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

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

    public String getPublish_date() {
        return publish_date;
    }

    public void setPublish_date(String publish_date) {
        this.publish_date = publish_date;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public double getPrice() {
        return price;
    }

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

    @Override
    public String toString() {
        return "Book{" + "name=" + name + ", author=" + author + ", publish_date=" + publish_date + ", publisher=" + publisher + ", price=" + price + '}';
    }
    
    public void input(){
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter book's name: ");
        this.name = scan.nextLine();
        System.out.println("Enter book's author: ");
        this.author = scan.nextLine();
        System.out.println("Enter book's published date: ");
        this.publish_date = scan.nextLine();
        System.out.println("Enter book's publisher: ");
        this.publisher = scan.nextLine();
        System.out.println("Enter book's price: ");
        this.price = Double.parseDouble(scan.nextLine());
    }
    
    public void output(){
        System.out.println(toString());
    }
}
-------------------------------------------------------------------------------------

package lesson4;

import java.io.File;
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.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DeflaterInputStream;
import lesson2.Main;

public class Main_Book {

    static List<Book> booklist = new ArrayList<>();

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int choose;
        File file = new File("D://C1907L//data.txt");
        File file_obj = new File("D://C1907L//data.obj");
        do {
            showMenu();
            choose = Integer.parseInt(scan.nextLine());
            switch (choose) {
                case 1:
                    addBook();
                    break;
                case 2:
                    showBook();
                    break;
                case 3:
                    sortByAuthor();
                    break;
                case 4:
                    saveToFileObj(file_obj);
                    break;
                case 5:
                    saveToFileText(file);
                    break;
                case 6:
                    deflaterFile(file);
                    break;
                case 7:
                    readObjFile(file_obj);
                    break;
                case 8:
                    System.out.println("Exit");
                    break;
            }
        } while (choose != 8);
    }

    public static void showMenu() {
        System.out.println("1. Nhập thông tin N quấn sách");
        System.out.println("2. Hiển thị thông tin sách");
        System.out.println("3. Sắp xếp theo tên tác giả");
        System.out.println("4. Lưu thông tin sách vào file data.obj");
        System.out.println("5. Lưu thông tin mỗi quyển sách vào file data.txt");
        System.out.println("6. Nén file data.txt thành file data.dfl");
        System.out.println("7. Đọc dữ liệu từ file data.obj và hiển thị ra màn hình");
        System.out.println("8. Thoát");
        System.out.println("Lựa chọn của bạn: ");
    }

    public static void addBook() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Nhập số lượng sách cần thêm: ");
        int n = Integer.parseInt(scan.nextLine());
        for (int i = 0; i < n; i++) {
            Book book = new Book();
            book.input();
            booklist.add(book);
        }
    }

    public static void showBook() {
        booklist.forEach((book) -> {
            book.output();
        });
    }

    public static void sortByAuthor() {
        for (int i = 0; i < booklist.size() - 1; i++) {
            for (int j = i + 1; j < booklist.size(); j++) {
                if (booklist.get(i).getAuthor().compareTo(booklist.get(j).getAuthor()) > 0) {
                    Collections.swap(booklist, i, j);
                }
            }
        }
    }

    public static void saveToFileObj(File file) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        try {
            fos = new FileOutputStream(file, true);
            oos = new ObjectOutputStream(fos);
            
//            oos.writeObject(studentList);
            for (Book book : booklist) {
                oos.writeObject(book);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    

    public static void saveToFileText(File file_output) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file_output, true);

            String line;
            byte[] b;
            for (Book book : booklist) {
                line = book.getName() + "," + book.getAuthor() + "," + book.getPrice() + ","
                        + book.getPublish_date() + "," + book.getPublisher()+ "\n";
                b = line.getBytes();
                fos.write(b);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public static void deflaterFile(File file){
        FileInputStream fis = null;
        DeflaterInputStream dis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(file);
            dis = new DeflaterInputStream(fis);

            fos = new FileOutputStream("D://data.zip");

            int code;
            while ((code = dis.read()) != -1) {
                fos.write(code);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis != null) {
                try {
                    fis.close();

                } catch (IOException ex) {
                    Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (dis != null) {
                try {
                    dis.close();

                } catch (IOException ex) {
                    Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (fos != null) {
                try {
                    fos.close();

                } catch (IOException ex) {
                    Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public static void readObjFile(File file){
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            Object obj = null;
            while((obj = ois.readObject()) != null) {
                Book book = (Book) obj;
                System.out.println(book);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main_Book.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }    
    
}


avatar
trung [C1907L]
2020-05-03 10:55:42



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bookMgr;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author prdox
 */
public class Book implements Serializable{
    String name,author,publisher;
    float price;
    Date publishDate;

    public Book() {
    }

    public Book(String name, String author, String publisher, float price, Date publishDate) {
        this.name = name;
        this.author = author;
        this.publisher = publisher;
        this.price = price;
        this.publishDate = publishDate;
    }
    
    public void input() {
        Scanner inp = new Scanner(System.in);
        System.out.println("Input book name:");
        name = inp.nextLine();
        System.out.println("Input author name");
        author = inp.nextLine();
        System.out.println("Input publisher");
        publisher = inp.nextLine();
        System.out.println("Input price");
        price = Float.parseFloat(inp.nextLine());
        System.out.println("Input publish date (format dd/MM/yyyy)");
        try {
            publishDate = new SimpleDateFormat("dd/MM/yyyy").parse(inp.nextLine());
        } catch (ParseException ex) {
            Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public String toString() {
        return "Book{" + "name=" + name + ", author=" + author + ", publisher=" + publisher + ", price=" + price + ", publishDate=" + publishDate + '}';
    }
    
    public void output() {
        System.out.println(this);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    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 float getPrice() {
        return price;
    }

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

    public Date getPublishDate() {
        return publishDate;
    }

    public void setPublishDate(Date publishDate) {
        this.publishDate = publishDate;
    }
    
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bookMgr;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author prdox
 */
public class dataMgr {

    List<Book> bookList = null;
    private static dataMgr instance;

    public dataMgr() {
        bookList = new ArrayList<>();
    }

    public static synchronized dataMgr getInstance() {
        if (instance == null) {
            instance = new dataMgr();
        }
        return instance;
    }

    public List<Book> getBookList() {
        return bookList;
    }

    public void setBookList(List<Book> bookList) {
        this.bookList = bookList;
    }

}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bookMgr;

import java.io.EOFException;
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.Collections;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DeflaterInputStream;

/**
 *
 * @author prdox
 */
public class MenuController {

    private static MenuController instance = null;

    private MenuController() {

    }

    public synchronized static MenuController getInstance() {
        if (instance == null) {
            instance = new MenuController();
        }
        return instance;
    }

    public void showMenu() {
        System.out.println("1. Nhập thông tin N quấn sách");
        System.out.println("2. Hiển thị thông tin sách");
        System.out.println("3. Sắp xếp theo tên tác giả");
        System.out.println("4. Lưu thông tin sách vào file data.obj");
        System.out.println("5. Lưu thông tin mỗi quyển sách vào file data.txt theo định dạng (ten sách, tác giả, giá bán, ngày xuất bản, nhà xuất bản) mỗi quyển sách trên một dòng");
        System.out.println("6. Nén file data.txt thành file data.dfl");
        System.out.println("7. Đọc dữ liệu từ file data.obj và hiển thị ra màn hình");
        System.out.println("8. Thoát");
    }

    public void inputInfo() {
        Scanner inp = new Scanner(System.in);
        System.out.println("Input number of book(s)");
        int n = Integer.parseInt(inp.nextLine());
        for (int i = 0; i < n; i++) {
            System.out.println("Input information for book number" + (i + 1));
            Book newBook = new Book();
            newBook.input();
            dataMgr.getInstance().getBookList().add(newBook);
        }
    }

    public void outputInfo() {
        if (dataMgr.getInstance().getBookList().isEmpty()) {
            return;
        }
        dataMgr.getInstance().getBookList().forEach((book) -> {
            book.output();
        });
    }

    public void sortByAuthor() {
        for (int i = 0; i < dataMgr.getInstance().getBookList().size() - 1; i++) {
            for (int j = i + 1; j < dataMgr.getInstance().getBookList().size(); j++) {
                if (dataMgr.getInstance().getBookList().get(i).getAuthor().compareTo(dataMgr.getInstance().getBookList().get(j).getAuthor()) > 0) {
                    Collections.swap(dataMgr.getInstance().getBookList(), i, j);
                }
            }
        }
    }

    public void saveInfoToFile() {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream("data.obj");
            oos = new ObjectOutputStream(fos);
            for (Book book : dataMgr.getInstance().getBookList()) {
                oos.writeObject(book);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public void saveInfoToTextFile() {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("data.txt");
            for (Book book : dataMgr.getInstance().getBookList()) {
                fos.write((book.toString() + "\n").getBytes());
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public void deflateTextDataFile() {

        FileInputStream fis = null;
        DeflaterInputStream dis = null;
        FileOutputStream fos = null;
        
        try {
            fis = new FileInputStream("data.txt");
            dis = new DeflaterInputStream(fis);
            fos = new FileOutputStream("data.dfl");
            int code;
            while((code = dis.read()) != -1) {
                fos.write(code);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException ex) {
                    Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public void readFromObjFile() {
        FileInputStream fis = null;
        ObjectInputStream ois =null;
        
        try {
            fis = new FileInputStream("data.obj");
            ois = new ObjectInputStream(fis);
            Object obj = null;
            while (true) {
                try {
                    obj = ois.readObject();
                    Book book = (Book) obj;
                    book.output();
                } catch (EOFException e) {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bookMgr;

import java.util.Scanner;

/**
 *
 * @author prdox
 */
public class Main {
    public static void main(String[] args) {
        int choose;
        Scanner inp = new Scanner(System.in);
        do {
            MenuController.getInstance().showMenu();
            choose = Integer.parseInt(inp.nextLine());
            switch(choose) {
                case 1:
                    MenuController.getInstance().inputInfo();
                    break;
                case 2:
                    MenuController.getInstance().outputInfo();
                    break;
                case 3:
                    MenuController.getInstance().sortByAuthor();
                    break;
                case 4:
                    MenuController.getInstance().saveInfoToFile();
                    break;
                case 5:
                    MenuController.getInstance().saveInfoToTextFile();
                    break;
                case 6:
                    MenuController.getInstance().deflateTextDataFile();
                    break;
                case 7:
                    MenuController.getInstance().readFromObjFile();
                    break;
                case 8:
                    System.out.println("Bye !");
                    break;
                default:
                    System.out.println("Invalid input");
            }
        } while (choose != 8);
    }
}


avatar
Nguyễn Hoàng Anh [C1907L]
2020-04-30 11:23:18



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package april30inflaterbook;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Redmibook 14
 */
public class main {

    public static void menu() {
        System.out.println("1. Nhập thông tin N quấn sách");
        System.out.println("2. Hiển thị thông tin sách");
        System.out.println("3. Sắp xếp theo tên tác giả");
        System.out.println("4. Lưu thông tin sách vào file data.obj");
        System.out.println("5. Lưu thông tin mỗi quyển sách vào file data.txt");
        System.out.println("6. Exit");

    }

    public static void addBook(List<Book> bookList) {
        Scanner input = new Scanner(System.in);
        while (true) {
            Book book = new Book();
            book.input();
            bookList.add(book);
            System.out.println("Countine Y/N ?");
            String y = input.nextLine();
            if (y.equalsIgnoreCase("n")) {
                break;
            }
        }
    }

    public static void showBook(List<Book> bookList) {
        for (int i = 0; i < bookList.size(); i++) {
            bookList.get(i).display();
        }
    }

    public static void sortBookAuthor(List<Book> bookList) {
        for (int i = 0; i < bookList.size(); i++) {
            for (int j = i + 1; j < bookList.size(); j++) {
                if (bookList.get(i).Author.compareTo(bookList.get(j).Author) > 0) {
                    Book temp;
                    temp = bookList.get(i);
                    bookList.set(i, bookList.get(j));
                    bookList.set(j, temp);
                }
            }
        }
    }

    public static void saveFileObject(List<Book> bookList) {
        ObjectOutputStream oos = null;
        File file = new File("data.obj");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            oos = new ObjectOutputStream(new FileOutputStream("data.obj",true));
            oos.writeObject(bookList);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void saveFile(List<Book> bookList) {
        FileOutputStream fos = null;
        File file = new File("data.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            fos = new FileOutputStream("data.txt",true);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }

        for (Book value : bookList) {
            String line = value.toString() + "\n";
            byte[] b = line.getBytes();
            try {
                fos.write(b);
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if(fos != null){
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static void main(String[] args) {
        // TODO code application logic here
        List<Book> bookList = new ArrayList<>();
        Scanner input = new Scanner(System.in);
        while (true) {
            menu();
            int choice = Integer.parseInt(input.nextLine());
            switch (choice) {
                case 1:
                    addBook(bookList);
                    break;
                case 2:
                    showBook(bookList);
                    break;
                case 3:
                    sortBookAuthor(bookList);
                    break;
                case 4:
                    saveFileObject(bookList);
                    break;
                case 5:
                    saveFile(bookList);
                    break;
                case 6:
                    return;

            }
        }
    }

}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package april30inflaterbook;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;


/**
 *
 * @author Redmibook 14
 */
public class Book implements Serializable{

    String BookName, Author, Manufacturer;
    float Price;
    String PublishingDate;

    public Book() {
    }

    public String getBookName() {
        return BookName;
    }

    public String getAuthor() {
        return Author;
    }

    public String getManufacturer() {
        return Manufacturer;
    }

    public float getPrice() {
        return Price;
    }

    public void setBookName(String BookName) {
        this.BookName = BookName;
    }

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

    public void setManufacturer(String Manufacturer) {
        this.Manufacturer = Manufacturer;
    }

    public void setPrice(float Price) {
        this.Price = Price;
    }

    public void input() {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter book name : ");
        BookName = input.nextLine();
        System.out.println("Enter author name : ");
        Author = input.nextLine();
        System.out.println("Enter manufacture name : ");
        Manufacturer = input.nextLine();
        System.out.println("Enter book price : ");
        Price = Float.parseFloat(input.nextLine());
        System.out.println("Enter publishing date : ");
        String inputDate = input.nextLine();
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        Date date = new Date();

        try {
            date = formatter.parse(inputDate);
            PublishingDate = formatter.format(date);
        } catch (ParseException ex) {
            date.toInstant();
            PublishingDate = formatter.format(date);
        }

    }

    public void display() {
        System.out.println(toString());
    }

    @Override
    public String toString() {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        return "Book :" + "BookName=" + BookName + ", Author=" + Author + ", Manufacturer=" + Manufacturer + ", Price=" + Price + ", PublishingDate=" + PublishingDate;
    }

}


avatar
Ngô Quang Huy [C1907L]
2020-04-29 16:15:47



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package April29ZipFile;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author Administrator
 */
public class Book implements Serializable{
    String Name,Author,Date,NXB;
    Float Price;

    public Book() {
    }

    public Book(String Name, String Author, String Date, String NXB, Float Price) {
        this.Name = Name;
        this.Author = Author;
        this.Date = Date;
        this.NXB = NXB;
        this.Price = Price;
    }

    public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public String getAuthor() {
        return Author;
    }

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

    public String getDate() {
        return Date;
    }

    public void setDate(String Date) {
        this.Date = Date;
    }

    public String getNXB() {
        return NXB;
    }

    public void setNXB(String NXB) {
        this.NXB = NXB;
    }

    public Float getPrice() {
        return Price;
    }

    public void setPrice(Float Price) {
        this.Price = Price;
    }
    
    public void input(){
        Scanner input = new Scanner(System.in);
        System.out.print("Insert Name: ");
        Name = input.nextLine();
        System.out.print("Insert Author: ");
        Author = input.nextLine();
        System.out.print("Insert Price: ");
        Price = Float.parseFloat(input.nextLine());
        System.out.print("Insert Date: ");
        Date = input.nextLine();
        System.out.print("Insert NXB: ");
        NXB = input.nextLine();
    }

    @Override
    public String toString() {
        return Name + ", " + Author + ", " + Price + ", " + Date + ", " + NXB;
    }
    
    public void output(){
        System.out.println(toString());
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package April29ZipFile;

import java.io.File;
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.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DeflaterInputStream;

/**
 *
 * @author Administrator
 */
public class BookSave {
    static List<Book> bookList = new ArrayList<>();
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while(true){
            showMenu();
            int choose = input.nextInt();
            switch(choose){
                case 1:
                    addBook();
                    break;
                case 2:
                    showBook();
                    break;
                case 3:
                    sortBook();
                    break;
                case 4:
                    saveObjectBook();
                    break;
                case 5:
                    saveInfoBook();
                    break;
                case 6:
                    zipFile();
                    break;
                case 7:
                    readFile();
                    break;
                default:
                    System.exit(0);
                    break;
            }
        }
    }
    
    static void showMenu(){
        System.out.print("1. Nhập thông tin N quấn sách\n" +
            "2. Hiển thị thông tin sách\n" +
            "3. Sắp xếp theo tên tác giả\n" +
            "4. Lưu thông tin sách vào file data.obj\n" +
            "5. Lưu thông tin mỗi quyển sách vào file data.txt\n"+
            "6. Nén file data.txt thành file data.dfl\n" + 
            "7. Đọc dữ liệu từ file data.obj và hiển thị ra màn hình\n" + 
            "8. Thoát\n" + 
            "\t Choose: ");
    }
    
    static void addBook(){
        Scanner input = new Scanner(System.in);
        System.out.print("Enter number of book: ");
        int n= Integer.parseInt(input.nextLine());
        for(int i=0;i<n;i++){
            System.out.println("Book number: "+(i+1));
            Book book= new Book();
            book.input();
            bookList.add(book);
        }
    }
    
    static void showBook(){
        for (Book book : bookList) {
            book.output();
        }
    }
    
    static void sortBook(){
        for (int i=0;i<bookList.size()-1;i++) {
            for (int j = i+1; j < bookList.size(); j++) {
                if((bookList.get(i).getAuthor().compareTo(bookList.get(j).getAuthor()))!=-1){
                    Collections.swap(bookList, i, j);
                }
            }
        }
    }
    
    static void saveObjectBook(){
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            fos = new FileOutputStream("data.obj",true);
            oos = new ObjectOutputStream(fos);
            
            oos.writeObject(bookList);
            System.out.println("Save success.");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    static void saveInfoBook(){
        FileOutputStream fos =null;
        byte[] b;
        
        try {
            fos =new FileOutputStream("data.txt");
            for (Book book : bookList) {
                String line = book.toString()+"\n";
                b = line.getBytes();
                fos.write(b);
            }
            System.out.println("Save success.");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null ){
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    static void zipFile(){
        FileInputStream fis = null;
        DeflaterInputStream dis = null;
        FileOutputStream fos = null;
        
        try {
            fis = new FileInputStream("data.txt");
            dis = new DeflaterInputStream(fis);
            fos = new FileOutputStream("data.dfl");
            
            int code;
            while((code = dis.read())!=-1){
                fos.write(code);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(dis != null){
                try {
                    dis.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    static void readFile(){
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            fis = new FileInputStream("data.obj");
            ois = new ObjectInputStream(fis);
            
            List<Book> bkl = (List<Book>) ois.readObject();
            for (Book bk : bkl) {
                System.out.println(bk);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(ois != null){
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookSave.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


avatar
Luong Dinh Dai [T1907A]
2020-03-27 05:31:10



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package QuanLySach;

import java.util.Scanner;

/**
 *
 * @author FATE STORE
 */
public class Book {
    private String tensach, tacgia, giaban, ngayxb, nhasx;

    public Book() {
    }

    public Book(String tensach, String tacgia, String giaban, String ngayxb, String nhasx) {
        this.tensach = tensach;
        this.tacgia = tacgia;
        this.giaban = giaban;
        this.ngayxb = ngayxb;
        this.nhasx = nhasx;
    }

    public String getTensach() {
        return tensach;
    }

    public void setTensach(String tensach) {
        this.tensach = tensach;
    }

    public String getTacgia() {
        return tacgia;
    }

    public void setTacgia(String tacgia) {
        this.tacgia = tacgia;
    }

    public String getGiaban() {
        return giaban;
    }

    public void setGiaban(String giaban) {
        this.giaban = giaban;
    }

    public String getNgayxb() {
        return ngayxb;
    }

    public void setNgayxb(String ngayxb) {
        this.ngayxb = ngayxb;
    }

    public String getNhasx() {
        return nhasx;
    }

    public void setNhasx(String nhasx) {
        this.nhasx = nhasx;
    }

    @Override
    public String toString() {
        return "Book{" + "tensach=" + tensach + ", tacgia=" + tacgia + ", giaban=" + giaban + ", ngayxb=" + ngayxb + ", nhasx=" + nhasx + '}';
    }
    public void viewBook(){
        System.out.println(toString());
    }
    public void input(){
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhap ten sach: ");
        tensach = sc.nextLine();
        System.out.println("Nhap ten tac gia: ");
        tacgia = sc.nextLine();
        System.out.println("Nhap gia ban: ");
        giaban = sc.nextLine();
        System.out.println("Nhap ngay xuat ban: ");
        ngayxb = sc.nextLine();
        System.out.println("Nhap nha xuat ban: ");
        nhasx = sc.nextLine();
    }

    String getLine() {
        return tensach + "," + tacgia + "," + giaban + "," + ngayxb + "," + nhasx + "\n";
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package QuanLySach;

import java.io.BufferedOutputStream;
import java.io.File;
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.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DeflaterInputStream;

/**
 *
 * @author FATE STORE
 */
public class BookList {

    ArrayList<Book> lstbook;

    public BookList() {
        this.lstbook = new ArrayList<>();
    }

    public void addBook(Book book) {
        this.lstbook.add(book);
    }

    public void hienthi() {
        for (Book book : lstbook) {
            book.viewBook();
        }
    }

    public void sapxep() {
        Collections.sort(lstbook, new Comparator<Book>() {

            @Override
            public int compare(Book o1, Book o2) {
                return o1.getTacgia().compareToIgnoreCase(o2.getTacgia());
            }
        });
    }

    public void save() throws IOException {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            fos = new FileOutputStream(new File("C:\\Users\\FATE STORE\\Documents\\NetBeansProjects\\java01\\src\\QuanLySach\\data.obj"));
            oos = new ObjectOutputStream(fos);
            oos.writeObject(lstbook);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (oos != null) {
                oos.close();
            }
        }
    }

    public void read() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(new File("C:\\Users\\FATE STORE\\Documents\\NetBeansProjects\\java01\\src\\QuanLySach\\data.obj"));
            ois = new ObjectInputStream(fis);
            lstbook = (ArrayList<Book>) (List<Book>) ois.readObject();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BookList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BookList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(BookList.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookList.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookList.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public void saveFiledata() {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            String filename = "C:\\Users\\FATE STORE\\Documents\\NetBeansProjects\\java01\\src\\QuanLySach\\data.txt";
            fos = new FileOutputStream(filename);
            bos = new BufferedOutputStream(fos);
            //ghi du lieu vao file
            for (Book book : lstbook) {
                String line = book.getLine();
                try {
                    byte[] b = line.getBytes("utf8");
                    bos.write(b);

                } catch (UnsupportedEncodingException ex) {
                    Logger.getLogger(BookList.class
                            .getName()).log(Level.SEVERE, null, ex);
                } catch (IOException e) {
                    Logger.getLogger(BookList.class
                            .getName()).log(Level.SEVERE, null, e);
                }

            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(BookList.class
                    .getName()).log(Level.SEVERE, null, ex);
        } finally {

            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();

                }
            } catch (IOException e) {
                Logger.getLogger(BookList.class
                        .getName()).log(Level.SEVERE, null, e);
            }
        }

    }

    public void nenfile() {
        String filename = "C:\\Users\\FATE STORE\\Documents\\NetBeansProjects\\java01\\src\\QuanLySach\\data.txt";
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(filename);
            DeflaterInputStream dis = new DeflaterInputStream(fis);
            String newfile = "C:\\data.dfl";
            fos = new FileOutputStream(newfile);
            int count;
            while ((count = dis.read()) != -1) {
                fos.write(count);

            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BookList.class
                    .getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BookList.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package QuanLySach;

import java.io.IOException;
import java.util.Scanner;

/**
 *
 * @author FATE STORE
 */
public class Main {
    public static void main(String[] args) throws IOException {
        Main main = new Main();
        BookList bookList = new BookList();
        int sw;
        do{
            main.menu();
            Scanner sc = new Scanner(System.in);
            sw = sc.nextInt();
            sc.nextLine();
            switch(sw){
                case 1:
                    System.out.println("Nhap so cuon sach muon nhap vao: ");
                    int n = sc.nextInt();
                    sc.nextLine();
                    for(int i = 0; i<n;i++){
                        Book book = new Book();
                        book.input();
                        bookList.addBook(book);
                    }
                    break;
                case 2:
                    bookList.hienthi();
                    break;
                case 3:
                    bookList.sapxep();
                    break;
                case 4:
                    bookList.save();
                    break;
                case 5:
                    bookList.saveFiledata();
                    break;
                case 6:
                    bookList.nenfile();
                    break;
                case 7:
                    bookList.read();
                    bookList.hienthi();
                default:
                    System.out.println("Nhap lai: ");
                    break;
            }
        }
        while(sw!=8);
    }
    public void menu(){
        System.out.print("=========================================\n1: Nhap thong tin N cuon sach: \n2: Hien thi thong tin sach: \n3: Sap xep theo ten tac gia: \n4: Luu thong tin sach vao file data.obj: \n5: Luu thong tin moi cuon sach vao file data.txt: \n6: Nen file data.txt thanh file data.dfl: \n7: Doc du lieu file data.obj va hien thi: \n8: Thoat: ");
    }
}