By GokiSoft.com| 20:00 17/03/2023|
Java Advanced

Quản lý sách bằng Java - Lập trình Java BT1672

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 sách vào file data.obj

5. Lưu thông tin mỗi quấ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 quấn sách tren 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

6. Nên file data.txt thành file data.dfl

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

8. Thoát

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

https://gokisoft.com/1672

Bình luận

avatar
Nguyễn Hoàng Anh [C1907L]
2020-06-17 13:16:17



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

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.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import jdk.internal.org.objectweb.asm.commons.StaticInitMerger;

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

    /**
     * @param args the command line arguments
     */
    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 quấ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. Exit ");
        System.out.println("Choice : ");
    }

    public static void inputBook(List<Book> bookList) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter N books :");
        int N = Integer.parseInt(input.nextLine());
        for (int i = 0; i < N; i++) {
            System.out.println("Enter book " + (i + 1) + " information");
            Book book = new Book();
            book.input();
            bookList.add(book);
        }
    }

    public static void displayBook(List<Book> bookList) {
        for (int i = 0; i < bookList.size(); i++) {
            System.out.println("Book " + (i + 1) + " information");
            bookList.get(i).display();
        }
    }

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

    public static void saveFile(List<Book> bookList) {
        File file = new File("data.obj");
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            file.createNewFile();
            oos = new ObjectOutputStream(fos = new FileOutputStream(file));
            oos.writeObject(bookList);
        } catch (IOException ex) {
            Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException ex) {
                Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void saveFileTxt(List<Book> bookList) {
        File file = new File("data.txt");
        FileOutputStream fos = null;

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

    }

    public static void deflaterFile() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        DeflaterOutputStream dos = null;
        File file = new File("data.dfl");
        try {
            file.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            fis = new FileInputStream("data.txt");
            fos = new FileOutputStream(file);
            dos = new DeflaterOutputStream(fos);
            int oneByte;
            while ((oneByte = fis.read()) != -1) {
                dos.write(oneByte);
            }
            fis.close();
            dos.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void readBookList() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        List<Book> bookList = new ArrayList();
        try {
            ois = new ObjectInputStream(fis = new FileInputStream("data.obj"));
            bookList = (List<Book>) ois.readObject();
            for(Book book : bookList){
                book.display();
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException ex) {
                Logger.getLogger(TestJava.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static void main(String[] args) {
        // TODO code application logic here
        Scanner input = new Scanner(System.in);
        List<Book> bookList = new ArrayList();
        while (true) {
            menu();
            int choice = Integer.parseInt(input.nextLine());
            switch (choice) {
                case 1:
                    inputBook(bookList);
                    break;
                case 2:
                    displayBook(bookList);
                    break;
                case 3:
                    sortBookByAuthor(bookList);
                    break;
                case 4:
                    saveFile(bookList);
                    break;
                case 5:
                    saveFileTxt(bookList);
                    break;
                case 6:
                    deflaterFile();
                    break;
                case 7:
                    readBookList();
                    break;
                case 8:
                    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 testjava;

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

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

    String BookName, Author, DatePublished, Producer;

    Float BookPrice;

    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 getDatePublished() {
        return DatePublished;
    }

    public void setDatePublished(String DatePublished) {
        this.DatePublished = DatePublished;
    }

    public String getProducer() {
        return Producer;
    }

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

    public Float getBookPrice() {
        return BookPrice;
    }

    public void setBookPrice(Float BookPrice) {
        this.BookPrice = BookPrice;
    }

    public void input() {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter Book Name :");
        this.BookName = input.nextLine();
        System.out.println("Enter Author Name :");
        this.Author = input.nextLine();
        System.out.println("Enter Book Published Date :");
        this.DatePublished = input.nextLine();
        System.out.println("Enter Book Price :");
        this.BookPrice = Float.parseFloat(input.nextLine());
        System.out.println("Enter Producer Name :");
        this.Producer = input.nextLine();

    }
    public void display(){
        System.out.println(toString());
    }
    @Override
    public String toString() {
        return "Book{" + "BookName=" + BookName + ", Author=" + Author + ", DatePublished=" + DatePublished + ", Producer=" + Producer + ", BookPrice=" + BookPrice + '}';
    }
    
}


avatar
hoangkhiem [C1907L]
2020-06-17 12:41:37



/*
 * 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.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
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 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:
                    luudata((ArrayList<Book>) bookList);
                    break;
                case 6: {
                    try {
                        nenfiletxt((ArrayList<Book>) bookList);
                    } catch (IOException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                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 luudata(ArrayList<Book> booklist) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("data.txt");
            for (Book book : booklist) {
                fos.write((book.toString() + "\n").getBytes());
            }
        } catch (FileNotFoundException ex) {

        } catch (IOException ex) {

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

    private static void nenfiletxt(ArrayList<Book> booklist) throws FileNotFoundException, IOException {
        String filename = "data.txt";
        FileInputStream fis = new FileInputStream(filename);
        DeflaterInputStream dis = new DeflaterInputStream(fis);
        String dfl = "data.dfl";
        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 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
Ngô Quang Huy [C1907L]
2020-06-17 12:25:21



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

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

/**
 *
 * @author student
 */
public class Book implements Serializable{
    String Name,Author,Producer,Date;
    int Price;

    public Book() {
    }

    public Book(String Name, String Author, String Producer, String Date, int Price) {
        this.Name = Name;
        this.Author = Author;
        this.Producer = Producer;
        this.Date = Date;
        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 getProducer() {
        return Producer;
    }

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

    public String getDate() {
        return Date;
    }

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

    public int getPrice() {
        return Price;
    }

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

    
    public void input(){
        Scanner input = new Scanner(System.in);
        System.out.println("Insert Book Name");
        Name = input.nextLine();
        System.out.println("Insert Book Author");
        Author = input.nextLine();
        System.out.println("Insert Book Price");
        Price = Integer.parseInt(input.nextLine());
        System.out.println("Insert Book Producer");
        Producer = input.nextLine();
        System.out.println("Insert Book Date");
        Date = input.nextLine();
    }

    @Override
    public String toString() {
        return Name + ", "+Author + ", "+ Price + ", "+Date + ", "+Producer;
    }
    
    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 BT;

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.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 student
 */
public class Main {
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
        List<Book> booklist = new ArrayList<>();
        while(true){
            showMenu();
            int choose = Integer.parseInt(input.nextLine());
            switch(choose){
                case 1:
                    System.out.print("Enter number of book: ");
                    int n = Integer.parseInt(input.nextLine());
                    for (int i = 0; i < n; i++) {
                        Book book = new Book();
                        book.input();
                        booklist.add(book);
                    }
                    break;
                case 2:
                    for (Book book : booklist) {
                        book.output();
                    }
                    break;
                case 3:
                    Collections.sort(booklist, new Comparator<Book>() {
                        @Override
                        public int compare(Book o1, Book o2) {
                            return o1.Author.compareTo(o2.Author);
                        }
                    });
                    
                    break;
                case 4:
                    FileOutputStream fos = null;
                    ObjectOutputStream oos = null;
                    
            {
                try {
                    fos = new FileOutputStream("data.obj");
                    oos = new ObjectOutputStream(fos);
                    
                    oos.writeObject(booklist);
                    System.out.println("Save Success\n");
                } 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);
                        }
                    }
                }
            }
                    
                    break;
                case 5:
                    FileOutputStream fos2 = null;
            {
                try {
                    fos2 = new FileOutputStream("data.txt");
                    for (Book booklist1 : booklist) {
                        fos2.write((booklist1.toString()+"\n").getBytes());
                    }
                    
                } 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(fos2!= null){
                        try {
                            fos2.close();
                        } catch (IOException ex) {
                            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
                    break;
                case 6:
                    FileInputStream fis3 = null;
                    DeflaterInputStream dis = null;
                    FileOutputStream fos3 = null;
                    
            {
                try {
                    fis3 = new FileInputStream("data.txt");
                    dis = new DeflaterInputStream(fis3);
                    fos3 = new FileOutputStream("data.zip");
                    int code;
                    while((code = dis.read())!=-1){
                        fos3.write(code);
                    }
                } 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(fis3!=null){
                        try {
                            fis3.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(fos3!=null){
                        try {
                            fos3.close();
                        } catch (IOException ex) {
                            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
                    break;
                case 7:
                    FileInputStream fis = null;
                    ObjectInputStream ois = null;
                    
            {
                try {
                    fis = new FileInputStream("data.obj");
                    ois = new ObjectInputStream(fis);
                    
                    booklist = (List<Book>) ois.readObject();
                    System.out.println("Read Success\n");
                } 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);
                } catch (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);
                        }
                    }
                }
            }
                    break;
                case 8:
                    System.exit(0);
                    break;
            }
        }
    }
    
    public static void showMenu(){
        System.out.println("\n1. Insert n book");
        System.out.println("2. Show book");
        System.out.println("3. Sort book");
        System.out.println("4. Save to data.obj");
        System.out.println("5. Save to data.txt");
        System.out.println("6. Compress to data.dfl");
        System.out.println("7. Read File");
        System.out.println("8. Exit");
        System.out.print("Choose: ");
    }
}


avatar
Hoàng Quang Huy [C1907L]
2020-06-17 12:22:16




package lesson4;

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

/**
 *
 * @author T480s
 */
public class Book implements Serializable{
    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.EOFException;
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://C1907L//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(true) {
                try{
                    obj = ois.readObject();
                    Book book = (Book) obj;
                    System.out.println(book);   
                }catch(EOFException e){
                    break;
                }
            }
        } 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-06-17 12:21:44



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

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

/**
 *
 * @author student
 */
public class Book implements Serializable{
    String bookName,author,producer,publishDate;
    Float price;

    public Book() {
    }
    
    public void input() {
        Scanner inp = new Scanner(System.in);
        System.out.println("book name ?");
        bookName = inp.nextLine();
        System.out.println("author ?");
        author = inp.nextLine();
        System.out.println("producer ?");
        producer = inp.nextLine();
        System.out.println("publish date: ?");
        publishDate = inp.nextLine();
        System.out.println("price: ?");
        price = Float.parseFloat(inp.nextLine());
    }

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

    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 getProducer() {
        return producer;
    }

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

    public Float getPrice() {
        return price;
    }

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

    public String getPublishDate() {
        return publishDate;
    }

    public void setPublishDate(String Date) {
        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 qls;

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.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 student
 */
public class Main {

    public static void main(String[] args) {
        List<Book> bookList = new ArrayList<>();
        Scanner inp = new Scanner(System.in);
        int choice = 0;
        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 quấn sách vào file data.txt theo định 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("Nhap vao lua chon: ...");
            choice = Integer.parseInt(inp.nextLine());
            switch (choice) {
                case 1:
                    System.out.println("Nhap vao so luong sach");
                    int N = Integer.parseInt(inp.nextLine());
                    for (int i = 0; i < N; i++) {
                        System.out.println("Nhap thong tin quyen sach thu" + (i + 1));
                        Book newBook = new Book();
                        newBook.input();
                        bookList.add(newBook);
                    }
                    break;
                case 2:
                    System.out.println("Thong tin danh sach book la:");
                    for (Book bk : bookList) {
                        bk.output();
                    }
                    break;
                case 3:
                    Collections.sort(bookList, new Comparator<Book>() {
                        @Override
                        public int compare(Book b2, Book b1) {
                            return b1.author.compareTo(b2.author);
                        }
                    });
                    break;
                case 4:
                    FileOutputStream fos = null;
                    ObjectOutputStream oos = null;
                    String currentDirectory = System.getProperty("user.dir");
                    System.out.println("The current working directory is " + currentDirectory);
                    try {
                        fos = new FileOutputStream("data.obj");
                        oos = new ObjectOutputStream(fos);
                        for (Book book : bookList) {
                            oos.writeObject(book);
                        }
                    } catch (FileNotFoundException ex) {
                    } catch (IOException ex) {
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException ex) {
                            }
                        }
                        if (oos != null) {
                            try {
                                oos.close();
                            } catch (IOException ex) {
                            }
                        }
                    }
                    break;
                case 5:
                    fos = null;
                    try {
                        fos = new FileOutputStream("data.txt");
                        for (Book book : bookList) {
                            fos.write((book.toString() + "\n").getBytes());
                        }
                    } catch (FileNotFoundException ex) {

                    } catch (IOException ex) {

                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException ex) {
                            }
                        }
                    }
                    break;
                case 6:
                    FileInputStream fis = null;
                    DeflaterInputStream dis = null;
                    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) {

                    } catch (IOException ex) {

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

                            }
                        }

                        if (dis != null) {
                            try {
                                dis.close();
                            } catch (IOException ex) {

                            }
                        }

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

                            }
                        }
                    }
                    break;
                case 7:
                    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) {
                        
                    } catch (IOException | ClassNotFoundException ex) {
                        
                    } finally {
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException ex) {
                                
                            }
                        }
                        if (ois != null) {
                            try {
                                ois.close();
                            } catch (IOException ex) {
                                
                            }
                        }
                    }
                    break;
                case 8:
                    System.out.println("bye");
                    break;
                default:
                    System.out.println("Invalid choice");
            }

        } while (choice
                != 8);

    }

}