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

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

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

thienphu [T1907A]
thienphu

2020-03-26 11:32:32



/*
 * 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 BTQuanliSach;

/**
 *
 * @author Thien Phu
 */
/*
 * 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.
 */
import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author Thien Phu
 */
public class Book implements Serializable {

    String tenSach, tenTg, gia, nhaXB, ngaySx;

    public Book() {
    }

    public Book(String tenSach, String tenTg, String gia, String ngayXb, String ngaySx) {
        this.tenSach = tenSach;
        this.tenTg = tenTg;
        this.gia = gia;
        this.nhaXB = ngayXb;
        this.ngaySx = ngaySx;
    }

    public String getTenSach() {
        return tenSach;
    }

    public void setTenSach(String tenSach) {
        this.tenSach = tenSach;
    }

    public String getTenTg() {
        return tenTg;
    }

    public void setTenTg(String tenTg) {
        this.tenTg = tenTg;
    }

    public String getGia() {
        return gia;
    }

    public void setGia(String gia) {
        this.gia = gia;
    }

    public String getNgayXb() {
        return nhaXB;
    }

    public void setNgayXb(String ngayXb) {
        this.nhaXB = ngayXb;
    }

    public String getNgaySx() {
        return ngaySx;
    }

    public void setNgaySx(String ngaySx) {
        this.ngaySx = ngaySx;
    }

    @Override
    public String toString() {
        return "Book{" + "tenSach=" + tenSach + ", tenTg=" + tenTg + ", gia=" + gia + ", ngayXb=" + nhaXB + ", ngaySx=" + ngaySx + '}';
    }

    public void input() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhap ten:");
        tenSach = sc.nextLine();
        System.out.println("Nhap ten Tac Gia:");
        tenTg = sc.nextLine();
        System.out.println("Nhap gia ban");
        gia = sc.nextLine();
        System.out.println("Nhap ngay san xuat");
        ngaySx = sc.nextLine();
        System.out.println("Nhap nha xuat ban");
        nhaXB = sc.nextLine();
    }

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

    public String getLine() {
        return tenSach + "," + tenTg + "," + gia + "," + ngaySx + "," + nhaXB + "\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 BTQuanliSach;

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.ObjectOutput;
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;
import java.util.zip.DeflaterInputStream;

/**
 *
 * @author Thien Phu
 */
public class BookManage {

    private List<Book> listbook = new ArrayList<>();

    public BookManage() {
    }

    public void addbook() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhap N thong tin quan sach:");
        int n = Integer.parseInt(sc.nextLine());
        for (int i = 0; i < n; i++) {
            Book bk = new Book();
            bk.input();
            listbook.add(bk);
        }
    }
 public void sortbyName() {
        Collections.sort(listbook, new Comparator<Book>() {

            @Override
            public int compare(Book o1, Book o2) {
                return o1.getTenTg().compareToIgnoreCase(o2.getTenTg());
            }
        });
    }
    public void hienthi() {
        for (Book listbook1 : listbook) {
            listbook1.display();
        }
    }

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

        try {
            fos = new FileOutputStream(new File("D:\\baitapjava\\BT1\\src\\BTQuanliSach\\data.obj"));
            oos = new ObjectOutputStream(fos);
            oos.writeObject(listbook);
        } 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("D:\\baitapjava\\BT1\\src\\BTQuanliSach\\data.obj"));
            ois = new ObjectInputStream(fis);
            listbook = (List<Book>) ois.readObject();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BookManage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BookManage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(BookManage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookManage.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(BookManage.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    //save file data
     public void saveFiledata() {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            String filename = "D:\\baitapjava\\BT1\\src\\BTQuanliSach\\data.txt";
            fos = new FileOutputStream(filename);
            bos = new BufferedOutputStream(fos);
            //ghi du lieu vao file
            for (Book book1 : listbook) {
                String line = book1.getLine();
                try {
                    byte[] b = line.getBytes("utf8");
                    bos.write(b);

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

            }

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

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

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

    }
     
     public void nenfile() {
        String filename = "D:\\baitapjava\\BT1\\src\\BTQuanliSach\\data.txt";
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(filename);
            DeflaterInputStream dis = new DeflaterInputStream(fis);
            String newfile = "D:\\baitapjava\\BT1\\src\\BTQuanliSach\\data.dfl";
            fos = new FileOutputStream(newfile);
            int count;
            while ((count = dis.read()) != -1) {
                fos.write(count);

            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BookManage.class
                    .getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BookManage.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 BTQuanliSach;

/**
 *
 * @author Thien Phu
 */
/*
 * 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.
 */
import java.io.IOException;
import java.util.Scanner;

/**
 *
 * @author Thien Phu
 */
public class Main {

    public static void main(String[] args) throws IOException {
        BookManage bkManage = new BookManage();
        Scanner sc = new Scanner(System.in);
        int choose;
        do {
            showmenu();
            choose = Integer.parseInt(sc.nextLine());
            switch (choose) {
                case 1:
                    bkManage.addbook();

                    break;
                case 2:
                    bkManage.hienthi();
                    break;
                case 3:
                    bkManage.sortbyName();
                    break;
                case 4:
                    bkManage.save();
                    break;
                case 5:
                    bkManage.saveFiledata();
                    break;
                case 6:
                    bkManage.nenfile();
                    break;
                case 7:
                    bkManage.read();
                    bkManage.hienthi();
                    break;
                case 8:
                    System.out.println("Thoat thanh cong");
                    break;
                default:
                    System.err.println("Chon lai di");
                    break;
            }

        } while (choose != 8);
    }

    public static void showmenu() {
        System.out.println("1:Nhap thong tin N quan sach");
        System.out.println("2:Hien thi thong tin 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 theo dinh dang");
        System.out.println("6:Nen file data.txt thanh file data.dfl");
        System.out.println("7:Doc du lieu tu file data.obj va hien thi ra man hinh");
        System.out.println("8: Thoat");
    }
}



nguyễn văn huy [T1907A]
nguyễn văn huy

2020-03-26 06:14:33



/*
 * 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 QLsach2;

import fiml.Main;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DeflaterInputStream;
import java.io.BufferedReader;
import java.io.FileReader;

/**
 *
 * @author ASUS
 */
public class main {

    public static void main(String[] args) throws IOException {
        ArrayList<book> booklist = new ArrayList<>();
        int choise, n;
        Scanner scan = new Scanner(System.in);
        do {
            menu();
            choise = Integer.parseInt(scan.nextLine());
            switch (choise) {
                case 1:
                    System.out.println("nhap thong tin cuon sach>>>.");
                    n = Integer.parseInt(scan.nextLine());
                    for (int i = 0; i < n; i++) {
                        book thao = new book();
                        thao.input();
                        booklist.add(thao);
                    }
                    break;
                case 2:
                    for (book thao : booklist) {
                        thao.display();
                    }
                    break;

                case 3:
                    Collections.sort(booklist, new Comparator<book>() {
                        @Override
                        public int compare(book o1, book o2) {
                            return o1.getName().compareToIgnoreCase(o2.getName());
                        }
                    });
                    break;
                case 4:
                    luubookobj(booklist);
                    break;
                case 5:
                    luumoicuontxt(booklist);
                    break;
                case 6:
                    nenfiletxt(booklist);
                    break;
                case 7:
                    hienthi(booklist);
                    break;
                case 8:
                    System.out.println("thoat!!!!");
                    break;
                default:
                    System.out.println("nhap lai de!!!1");
                    break;
            }
        } while (choise != 9);
    }

    static void menu() {
        System.out.println("1.nhap thong tin cuon sach");
        System.out.println("2.hien thi thong tin cuon sach");
        System.out.println("3.Sap xep theo ten tac gia");
        System.out.println("4.luu thong tin sach vao file data.obj");
        System.out.println("5.luu thong tin moi cuon sach vao data.txt");
        System.out.println("6.nen file data.txt thanh data.dfl");
        System.out.println("7.doc dl tu file data.obj vao hien thi ra man hinh");
        System.out.println("8.Thoat");
        System.out.println("9.choise");
    }

    private static void luubookobj(ArrayList<book> booklist) throws FileNotFoundException, IOException {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream("E:/file/mydata.obj");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(booklist);
        } catch (FileNotFoundException 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 luumoicuontxt(ArrayList<book> booklist) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            String filename = "data.txt";
            fos = new FileOutputStream(filename);
            bos = new BufferedOutputStream(fos);
            for (book thao : booklist) {
                String line = thao.getLine();
                byte[] t;
                try {
                    t = line.getBytes("utf8");
                    bos.write(t);
                } 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);
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private static void nenfiletxt(ArrayList<book> booklist) throws FileNotFoundException, IOException {
        String filename = "data.txt";
        FileInputStream fis = new FileInputStream(filename);//tao dl de doc
        DeflaterInputStream dis = new DeflaterInputStream(fis);//doc dl fis va nen luon
        String dfl = "data.dfl";//sang file moi
        FileOutputStream fos = new FileOutputStream(dfl);
        int code = 0;
        while ((code = dis.read()) != -1) {
            fos.write(code);
        }
        fos.close();
        dis.close();
        fis.close();
    }

    private static void hienthi(ArrayList<book> booklist) throws FileNotFoundException {
        FileReader fil = null;
        BufferedReader buff = null;
        try {
            String filename = "data.txt";
            fil = new FileReader(filename);
            buff = new BufferedReader(fil);
            String thaobeo = null;
            while ((thaobeo = buff.readLine()) != null) {
                book thao = new book();
                thao.parseLine(thaobeo);
                booklist.add(thao);
            }
        } 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 {
                if (buff != null) {
                    buff.close();
                }
                if (fil != null) {
                    fil.close();
                }
            } 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 QLsach2;

import java.util.*;

/**
 *
 * @author ASUS
 */
public class book {

    String bookname, name, nhasx;
    float giaban, ngaysx;

    public book() {
    }

    public book(String bookname, String name, String nhasx, float giaban, float ngaysx) {
        this.bookname = bookname;
        this.name = name;
        this.nhasx = nhasx;
        this.giaban = giaban;
        this.ngaysx = ngaysx;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public String getName() {
        return name;
    }

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

    public String getNhasx() {
        return nhasx;
    }

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

    public float getGiaban() {
        return giaban;
    }

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

    public float getNgaysx() {
        return ngaysx;
    }

    public void setNgaysx(float ngaysx) {
        this.ngaysx = ngaysx;
    }

    public void input() {
        Scanner scan = new Scanner(System.in);
        System.out.println("nhap tean sach");
        bookname = scan.nextLine();
        System.out.println("nhap ten tac gia:");
        name = scan.nextLine();
        System.out.println("nhap ten nha suat ban:");
        nhasx = scan.nextLine();
        System.out.println("nhap gia ban:");
        giaban = Float.parseFloat(scan.nextLine());
        System.out.println("nhap ngay san xuat:");
        ngaysx = Float.parseFloat(scan.nextLine());
    }

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

    @Override
    public String toString() {
        return "book{" + "bookname=" + bookname + ", name=" + name + ", nhasx=" + nhasx + ", giaban=" + giaban + ", ngaysx=" + ngaysx + '}';
    }
    String getLine() {
        return name + "," + bookname + "," + nhasx + "," + giaban + "," + ngaysx + "\n";
    }
    public void parseLine(String line){
        line=line.trim();
        String [] thao=line.split(line);
        if(thao.length<5){
            System.out.println("!!!!!!!");
            return;
        }
        name=thao[0];
        bookname=thao[1];
        nhasx=thao[2];
        giaban=Float.parseFloat(thao[3]);
        ngaysx=Float.parseFloat(thao[4]);
    }

}



Đỗ Văn Huấn [T1907A]
Đỗ Văn Huấn

2020-03-26 03:54:05



package java2_Advanced.BaiTapNgay25_3_2020.SachVaLuuThongTinTrenFile;

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

public class Book implements Serializable {
    String nameBook, nameAuthor, price, publicationDate, publishingCompany;

    public Book() {
    }

    public Book(String nameBook, String nameAuthor, String price, String publicationDate, String publishingCompany) {
        this.nameBook = nameBook;
        this.nameAuthor = nameAuthor;
        this.price = price;
        this.publicationDate = publicationDate;
        this.publishingCompany = publishingCompany;
    }

    public void nhap() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Nhap ten sach: ");
        nameBook = scan.nextLine();
        System.out.println("Nhap ten tac gia: ");
        nameAuthor = scan.nextLine();
        System.out.println("Nhap gia ban: ");
        price = scan.nextLine();
        System.out.println("Nhap ngay xuat ban: ");
        publicationDate = scan.nextLine();
        System.out.println("Nhap nha xuat ban: ");
        publishingCompany = scan.nextLine();
    }

    public void hienThi() {
        System.out.println(this);
    }

    @Override
    public String toString() {
        return "Book{" +
                "nameBook='" + nameBook + '\'' +
                ", nameAuthor='" + nameAuthor + '\'' +
                ", price='" + price + '\'' +
                ", publicationDate='" + publicationDate + '\'' +
                ", publishingCompany='" + publishingCompany + '\'' +
                '}';
    }

    public String getNameBook() {
        return nameBook;
    }

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

    public String getNameAuthor() {
        return nameAuthor;
    }

    public void setNameAuthor(String nameAuthor) {
        this.nameAuthor = nameAuthor;
    }

    public String getPrice() {
        return price;
    }

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

    public String getPublicationDate() {
        return publicationDate;
    }

    public void setPublicationDate(String publicationDate) {
        this.publicationDate = publicationDate;
    }

    public String getPublishingCompany() {
        return publishingCompany;
    }

    public void setPublishingCompany(String publishingCompany) {
        this.publishingCompany = publishingCompany;
    }

    public String getLine() {
        return nameBook + ", " + nameAuthor + ", " + price + ", " + publicationDate + ", " + publishingCompany + ", " + "\n";
    }
}



package java2_Advanced.BaiTapNgay25_3_2020.SachVaLuuThongTinTrenFile;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Perform perform = new Perform();
        Scanner scan = new Scanner(System.in);
        int choose;
        do {
            System.out.println("Nhap choose:");
            choose = Integer.parseInt(scan.nextLine());
            switch (choose) {
                case 1:
                    perform.input();
                    break;
                case 2:
                    perform.display();
                    break;
                case 3:
                    perform.sortAuthor();
                    break;
                case 4:
                    perform.saveBook1_Object();
                    break;
                case 5:
                    perform.saveBook_buffered();
                    break;
                case 6:
                    perform.zipFile();
                    break;
                case 7:
                    perform.showBook1_Object();
                    break;
                case 8:
                    System.out.println("thoat");
                    break;
                default:
                    System.err.println("Nhap sai !!!");
                    break;
            }
        } while (choose != 8);
    }

    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 (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");
    }
}



package java2_Advanced.BaiTapNgay25_3_2020.SachVaLuuThongTinTrenFile;

import org.w3c.dom.ls.LSOutput;

import java.io.*;
import java.util.*;
import java.util.zip.DeflaterInputStream;

public class Perform {
    Scanner scan = new Scanner(System.in);
    List<Book> list = new ArrayList<>();

    //case1
    public void input() {
        System.out.println("Nhap so cuon sach:");
        int n = Integer.parseInt(scan.nextLine());
        for (int i = 0; i < n; i++) {
            Book book = new Book();
            book.nhap();
            list.add(book);
        }
    }

    //case2
    public void display() {
        for (Book book1 : list) {
            book1.hienThi();
        }
    }

    //case3
    public void sortAuthor() {
        Collections.sort(list, new Comparator<Book>() {
            @Override
            public int compare(Book book, Book t1) {
                return book.getNameAuthor().compareToIgnoreCase(book.getNameAuthor());
            }
        });
    }

    //case4
    public void saveBook1_Object() {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream("d:/Admin/Java2_advanced/data.obj");
            oos = new ObjectOutputStream(fos);

            oos.writeObject(list);

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

    //case5
    public void saveBook_buffered() {
        FileOutputStream fos = null;
        BufferedOutputStream bfos = null;
        try {
            fos = new FileOutputStream("d:/Admin/Java2_advanced/data.txt");
            bfos = new BufferedOutputStream(fos);

            for (Book book2 : list) {
                String line = book2.getLine();
                byte[] bytes = line.getBytes("utf-8");
                bfos.write(bytes);
            }

        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bfos != null) {
                try {
                    bfos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //case6
    public void zipFile() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        DeflaterInputStream dis = null;

        try {
            fis = new FileInputStream("d:/Admin/Java2_advanced/data.txt");
            dis = new DeflaterInputStream(fis);
            fos = new FileOutputStream("d:/Admin/Java2_advanced/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();
                }
            }
        }
    }

    //case7
    public void showBook1_Object() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream("d:/Admin/Java2_advanced/data.obj");
            ois = new ObjectInputStream(fis);

            ArrayList<Book> List = (ArrayList<Book>) ois.readObject();

            for (Book object : List) {
                object.hienThi();
            }

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

}



Trương Công Vinh [T1907A]
Trương Công Vinh

2020-03-25 11:17:15



/*
 * 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 Book_file;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DeflaterInputStream;
import java.util.zip.DeflaterOutputStream;

/**
 *
 * @author DELL
 */
public class main {
    static Scanner scan = new Scanner(System.in);
    public static void main(String[] args) {
        ArrayList<book> bookList = new ArrayList<>();
        int c;
        do {        
            menu();
            c= Integer.parseInt(scan.nextLine());
            switch(c){
                case 1:
                    addInfoBook(bookList);
                    break;
                case 2:
                    dispalayInforBook(bookList);
                    break;
                case 3:
                    sortBookByAuthor(bookList);
                    dispalayInforBook(bookList);
                    break;
                case 4:
                    saveInfoBooktoFile(bookList);
                    break;
                case 5:
                    saveToFile(bookList);
                    break;
                case 6:
                    DeflateFile();
                    break;
                case 7:
                    readFile();
                    
                    break;
                case 8:
                default:
                    break;
                
            }
            
        } while (c<8);
        
    }
    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 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");
        System.out.println("Lua chon : ");
    }

    private static void addInfoBook(ArrayList<book> bookList) {
        System.out.println("so luong (n) cuon sach can nhap : ");
        int n= Integer.parseInt(scan.nextLine());
        for (int i = 0; i < n; i++) {
            book book = new book();
            book.input();
            bookList.add(book);
        }
    }

    private static void dispalayInforBook(ArrayList<book> bookList) {
           for (int i = 0; i < bookList.size(); i++) {
            bookList.get(i).display();
        }
    }

    private static void sortBookByAuthor(ArrayList<book> bookList) {
          Collections.sort(bookList, new Comparator<book>() {
              @Override
              public int compare(book o1, book o2) {
                     return o1.getAuthor().compareToIgnoreCase(o2.getAuthor());
              }
          });
    }

    private static void saveToFile(ArrayList<book> bookList) {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream("d:/Java2/data.txt");
            bos = new BufferedOutputStream(fos);
            
            for (book object : bookList) {
                String line = object.getline();
                byte[] b;
                
                b = line.getBytes("utf8");
                bos.write(b);
            }
        } catch (IOException ex) {
            System.err.println("Loi ghi file  : "+ex);
        }finally{
            if (bos != null) {
                try {
                    bos.close();
                } 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);
                }
            }
        }
    }

    private static void saveInfoBooktoFile(ArrayList<book> bookList) {
         FileOutputStream fos =null;
         ObjectOutputStream oos = null;
         try {
            fos = new FileOutputStream("d:/Java2/data.obj");
            oos = new ObjectOutputStream(fos);
            
            oos.writeObject(bookList);
            
        } catch (IOException ex) {
             System.err.println("Loi ghi file : " + 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 DeflateFile() {
          FileOutputStream fos =null;
          DeflaterInputStream dis = null;
          FileInputStream fis = null;
          try {
            fis = new FileInputStream("d:/Java2/data.txt");
            dis = new DeflaterInputStream(fis);
            
            fos = new FileOutputStream("d:/Java2/data.dfl");
            
            int code;
              while ((code = dis.read()) != - 1) {                  
                  fos.write(code);
              }
              
            
        } catch (IOException ex) {
              System.err.println("Loi nen file : "+ ex);
        }finally{
              if (fos != null) {
                  try {
                      fos.close();
                  } catch (IOException ex) {
                      Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                  }
              }
              if (dis != null) {
                  try {
                      dis.close();
                  } catch (IOException ex) {
                      Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                  }
              }
              if (fis != null) {
                  try {
                      fis.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("d:/Java2/data.obj");
            ois = new ObjectInputStream(fis);
            
          ArrayList<book>  bookList = (ArrayList<book>) ois.readObject();
            
              for (book object : bookList) {
                  object.display();
              }
            
        } catch (IOException ex) {
              System.err.println("Loi doc file : "+ex);
        } catch (ClassNotFoundException 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 Book_file;

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

/**
 *
 * @author DELL
 */
public class book implements Serializable{
    String bookname , author, nhaXB , ngayXB;
    float price;

    public book() {
    }

    public book(String bookname, String author, String nhaXB, String ngayXB, float price) {
        this.bookname = bookname;
        this.author = author;
        this.nhaXB = nhaXB;
        this.ngayXB = ngayXB;
        this.price = price;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public String getAuthor() {
        return author;
    }

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

    public String getNhaXB() {
        return nhaXB;
    }

    public void setNhaXB(String nhaXB) {
        this.nhaXB = nhaXB;
    }

    public String getNgayXB() {
        return ngayXB;
    }

    public void setNgayXB(String ngayXB) {
        this.ngayXB = ngayXB;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }
    
    public void input(){
        Scanner scan = new Scanner(System.in);
        System.out.println("book name : ");
        bookname = scan.nextLine();
        System.out.println("author : ");
        author = scan.nextLine();
        System.out.println("nha xuat ban : ");
        nhaXB = scan.nextLine();
        System.out.println("ngay xuat ban : ");
        ngayXB = scan.nextLine();
        System.out.println("gia ban : ");
        price = Float.parseFloat(scan.nextLine());
        
    }

    @Override
    public String toString() {
        return "book{" + "bookname=" + bookname + ", author=" + author + ", nhaXB=" + nhaXB + ", ngayXB=" + ngayXB + ", price=" + price + '}';
    }
    public void display(){
        System.out.println(toString());
    }
    
    public String getline(){
        return bookname + "," + author + ","+ price+ ","  + nhaXB + "," + ngayXB  + "\n";
    }
    
}