By GokiSoft.com| 15:40 02/11/2022|
Java Advanced

[Source Code] Tìm hiểu về File & nén File trong Java - C2109I

VViết chương trình quản lý sách:
	Book:
		bookno
		bookName
		price

	Nhập thông tin sách
	Hiển thị thông tin sách
	Lưu
		Object -> dễ: khá dễ
		Text -> xử lý như thế nào?
	Read
		Object -> dễ: khá dễ
		Text -> xử lý như thế nào?

1) bookno: B001, bookName: Lap Trinh C, price: 100000
2) bookno: B002, bookName: HTML/CSS/JS, price: 120000
2) bookno: B003, bookName: SQL, price: 200000

Lưu:
	Ý tưởng:
		Lưu mỗi 1 quấn sách trên 1 dòng
			Giải pháp 1)
			bookno: B001, bookName: Lap Trinh C, price: 100000
			bookno: B001, bookName: Lap Trinh C, price: 100000
			bookno: B001, bookName: Lap Trinh C, price: 100000

			Giải pháp 2)
			B001, Lap Trinh C, 100000
			B002, HTML/CSS/JS, 120000
			B003, SQL, 2000000
Đọc:
	Đọc ra -> chuyển nó về mảng object book -> sử dụng được trong chương trình


=============================================
Nén dữ liệu:
	Nén 1 biến String trong Java
	Nén file (file text) -> nén -> file zip -> giải nén -> file gốc ban đầu 

Dữ liệu thô (dữ liệu text)
	~~~~~~~
	1 ký tự -> 3 byte => 24 bits -> lưu 1 ký tự

	1000 ký tự -> 3000 byte -> 3KB

Giải pháp:
	20 ký tự -> mã hoá byte/bit -> 5 bits -> 32 ký tự khác nhau = 3000 * 25% = 750B


Dữ liệu nén:
	Table header -> lữu thông tin nén
		A -> 00001
		B -> 00010
		...

	0000100010....
ZIP:

00001 -> A
...
...
...
...
-------------------------------------------------------

#Book.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package java2.lesson03;

import java.util.Scanner;

/**
 *
 * @author diepvan
 */
public class Book {
    String bookNo, bookName;
    int price;

    public Book() {
    }

    public String getBookNo() {
        return bookNo;
    }

    public void setBookNo(String bookNo) {
        this.bookNo = bookNo;
    }

    public String getBookName() {
        return bookName;
    }

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

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
    
    public void input() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("======= THONG TIN SACH =======");
        System.out.println("Nhap ma sach: ");
        bookNo = scan.nextLine();
        System.out.println("Nhap ten sach: ");
        bookName = scan.nextLine();
        System.out.println("Nhap gia: ");
        price = Integer.parseInt(scan.nextLine());
    }

    @Override
    public String toString() {
        return "bookNo: " + bookNo + ", bookName: " + bookName + ", price: " + price + "\n";
    }
    
    public void display() {
        System.out.println(this);
    }
    
    public void readFileLine(String line) {
        String[] arr = line.split(",");
        //Xu ly bookNo
        String[] bookNoList = arr[0].split(":");
        bookNo = bookNoList[1].trim();
        
        //Xu ly bookName
        String[] bookNameList = arr[1].split(":");
        bookName = bookNameList[1].trim();
        
        //Xu ly price
        String[] priceList = arr[2].split(":");
        price = Integer.parseInt(priceList[1].trim());
    }
}

#Main.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package java2.lesson03;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author diepvan
 * 
 * a1 -> 6, 2, 4, 10 -> 2, 4, 6, 10
i = 0

curr = 2 (a1.get(i))
next = 4 (a1.get(i + 1))

v = curr + 1
while: v < next
	a2.add(v)
	v++

i = 1
curr = 4
next = 6
	...

i = 2
curr = 6
next = 10
	...

i = 3
curr = 10
next = ???


a2 = 3, 5, 7, 8, 9
a1 + a2 = 2, 3, 4, 5, 6, 7, 8, 9, 10


a2 -> 3, 5, 7
a -> 2, 3, 4, 5, 6, 7, 8
 */
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        List<Integer> a1 = new ArrayList<>();
        
        //B1. Nhap thong tin du lieu
        System.out.println("Nhap so phan tu a1 = ");
        int N = Integer.parseInt(scan.nextLine());
        
        for (int i = 0; i < N; i++) {
            System.out.println("Nhap phan tu a1["+i+"] = ");
            int a = Integer.parseInt(scan.nextLine());
            
            a1.add(a);
        }
        
        //B2. Sap xep phan tu trong mang a1 -> tang dan
        Collections.sort(a1);
        
        //B3. Khai bao mang a2
        List<Integer> a2 = new ArrayList<>();
        
        //B4. Nhap du lieu con thieu
        int maxIndex = a1.size() - 1;
        for (int i = 0; i < maxIndex; i++) {
            int curr = a1.get(i);
            int next = a1.get(i + 1);
            int v = curr + 1;
            while(v < next) {
                a2.add(v);
                v++;
            }
        }
        
        System.out.println("===============================");
        //B5. Hien thi thong tin mang a2
        for (Integer v : a2) {
            System.out.println(v);
        }
    }
}

#Test.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package java2.lesson03;

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

/**
 *
 * @author diepvan
 */
public class Test {
    static List<Book> bookList = new ArrayList<>();
    
    public static void main(String[] args) {
//        inputData();
        
        //Cau 1) Luu du lieu
//        saveFile();
        readFile();
        
        System.out.println("=== THONG TIN SACH ===");
        for (Book book : bookList) {
            book.display();
        }
    }
    
    static void inputData() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Nhap so sach can them: ");
        int n = Integer.parseInt(scan.nextLine());
        
        for (int i = 0; i < n; i++) {
            Book b = new Book();
            b.input();
            
            bookList.add(b);
        }
    }
    
    static void saveFile() {
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream("books.txt");
            
            for (Book book : bookList) {
                String content = book.toString();
                byte[] data = content.getBytes("utf8");
                
                fos.write(data);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException 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(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        System.out.println("Save done!!!");
    }
    
    static void readFile() {
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        
        try {
            reader = new FileReader("books.txt");
            bufferedReader = new BufferedReader(reader);
            
            String line = null;
            
            while((line = bufferedReader.readLine()) != null) {
                if(line.trim().isEmpty()) continue;
                
                Book book = new Book();
                book.readFileLine(line);
                
                bookList.add(book);
            }
        } 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(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

#ZipTest.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package java2.lesson03;

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.DeflaterOutputStream;

/**
 *
 * @author diepvan
 */
public class ZipTest {
    public static void main(String[] args) {
        FileInputStream fis = null;
        DeflaterOutputStream dos = null;
        FileOutputStream fos = null;
        
        try {
            fis = new FileInputStream("data.txt");
            
            fos = new FileOutputStream("data.zip");
            dos = new DeflaterOutputStream(fos);
            
            int code;
            
            while((code = fis.read()) != -1) {
                dos.write(code);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ZipTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ZipTest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(ZipTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(dos != null) {
                try {
                    dos.close();
                } catch (IOException ex) {
                    Logger.getLogger(ZipTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(ZipTest.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)

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó