By GokiSoft.com| 19:57 17/03/2023|
Java Advanced

[Source Code] ObjectInputStram & ObjecOutputStream - Nén & Giải Nén File - C2206L

#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 com.gokisoft.bt1091;

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

/**
 *
 * @author teacher
 */
public class Book implements Serializable{
    String bookName;
    String authorName;
    float price;
    String releasedDate;
    String manufacturerName;

    public Book() {
    }

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

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

    public String getReleasedDate() {
        return releasedDate;
    }

    public void setReleasedDate(String releasedDate) {
        this.releasedDate = releasedDate;
    }

    public String getManufacturerName() {
        return manufacturerName;
    }

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

    @Override
    public String toString() {
        return "bookName=" + bookName + ", authorName=" + authorName + ", price=" + 
                price + ", releasedDate=" + releasedDate + ", manufacturerName=" + manufacturerName;
    }
    
    public String getFileLine() {
        return bookName + ", " + authorName + ", " + 
                price + ", " + releasedDate + ", " + manufacturerName + "\n";
    }
    
    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 tac gia: ");
        authorName = scan.nextLine();
        System.out.println("Nhap gia: ");
        price = Float.parseFloat(scan.nextLine());
        System.out.println("Ngay xuat ban: ");
        releasedDate = scan.nextLine();
        System.out.println("Nam xuat ban: ");
        manufacturerName = scan.nextLine();
    }
    
    public void parse(String line) {
        try {
            String arr[] = line.split(", ");
            bookName = arr[0];
            authorName = arr[1];
            price = Float.parseFloat(arr[2]);
            releasedDate = arr[3];
            manufacturerName = arr[4];
        } catch(Exception e) {
        }
    }
}

#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 com.gokisoft.bt1091;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
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 teacher
 */
public class Main {
    static List<Book> bookList = new ArrayList<>();
    static Scanner scan = new Scanner(System.in);
    
    public static void main(String[] args) {
        int choose;
        
        do {            
            showMenu();
            choose = Integer.parseInt(scan.nextLine());
            
            switch(choose) {
                case 1:
                    input();
                    break;
                case 2:
                    display();
                    break;
                case 3:
                    sortByAuthor();
                    break;
                case 4:
                    saveFile();
                    break;
                case 5:
                    readFile();
                    break;
                case 6:
                    saveBinaryFile();
                    break;
                case 7:
                    readBinaryFile();
                    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 file books.txt");
        System.out.println("5. Doc file books.txt");
        System.out.println("6. Luu file books.dat");
        System.out.println("7. Doc file books.dat");
        System.out.println("8. Thoat");
        System.out.println("Chon: ");
    }

    private static void input() {
        System.out.println("Nhap so sach can them: ");
        int N = Integer.parseInt(scan.nextLine());
        
        System.out.println("===== BAT DAU NHAP ======");
        for (int i = 0; i < N; i++) {
            System.out.println("+ Nhap quan sach: " + (i + 1));
            Book book = new Book();
            book.input();
            
            bookList.add(book);
        }
        System.out.println("===== KET THUC NHAP =====");
    }

    private static void display() {
        System.out.println("===== DANH SACH SACH ===== ");
        for (Book book : bookList) {
            book.display();
        }
    }

    private static void sortByAuthor() {
        Collections.sort(bookList, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                return o1.getAuthorName().compareToIgnoreCase(o2.getAuthorName());
            }
        });
        System.out.println("===== KET QUA SAU SAP XEP =====");
        display();
    }

    private static void saveFile() {
        String filename = "books.txt";
        
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream(filename);
            
            for (Book book : bookList) {
                byte[] data = book.getFileLine().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);
                }
            }
        }
        
        System.out.println("===== GHI FILE THANH CONG =====");
    }

    private static void readFile() {
        String filename = "books.txt";
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        
        try {
            reader = new FileReader(filename);
            bufferedReader = new BufferedReader(reader);
            
            String line;
            
            while((line = bufferedReader.readLine()) != null) {
                line = line.trim();
                if(!line.isEmpty()) {
                    Book book = new Book();
                    book.parse(line);
                    
                    bookList.add(book);
                }
            }
        } 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(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        System.out.println("===== DOC FILE THANH CONG =====");
    }

    private static void saveBinaryFile() {
        String filename = "books.dat";
        
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        try {
            fos = new FileOutputStream(filename);
            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(oos != null) {
                try {
                    oos.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);
                }
            }
        }
        
        System.out.println("===== LUU FILE NHI PHAN THANH CONG =====");
    }

    private static void readBinaryFile() {
        String filename = "books.dat";
        
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            fis = new FileInputStream(filename);
            ois = new ObjectInputStream(fis);
            
            bookList = (List<Book>) ois.readObject();
        } 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(ois != null) {
                try {
                    ois.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);
                }
            }
        }
        
        System.out.println("===== DOC FILE THANH CONG =====");
    }
}

#Test.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 com.gokisoft.bt1091;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DeflaterInputStream;
import java.util.zip.InflaterOutputStream;

/**
 *
 * @author teacher
 */
public class Test {
    public static void main(String[] args) {
//        zip();
        upzip();
    }
    
    static void zip() {
        String file = "vidu.txt";
        String zipFile = "vidu_test.zip";
        
        FileInputStream fis = null;
        DeflaterInputStream dis = null;
        FileOutputStream fos = null;
        
        try {
            fis = new FileInputStream(file);
            dis = new DeflaterInputStream(fis);
            
            fos = new FileOutputStream(zipFile);
            
            int code;
            while((code = dis.read()) != -1) {
                fos.write(code);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(dis != null) {
                try {
                    dis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
    }

    private static void upzip() {
        String file = "vidu_test.zip";
        String unzipFile = "vidu_test.txt";
        
        FileInputStream fis = null;
        
        InflaterOutputStream ios = null;
        FileOutputStream fos = null;
        
        try {
            fis = new FileInputStream(file);
            
            fos = new FileOutputStream(unzipFile);
            ios = new InflaterOutputStream(fos);
            
            int code;
            
            while((code = fis.read()) != -1) {
                ios.write(code);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(ios != null) {
                try {
                    ios.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
    }
}
Tags:

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

5

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