Bài 212: ZIP file trong java

Ngày đăng: 1/6/2023 11:04:00 AM

Trong bài này chúng ta sẽ học về làm thế nào để ZIP file trong java. Vậy thì ZIP là gì? ZIP là định dạng file mà ở đó data của file được mã hóa và nén lại, độ nén phụ thuộc vào dữ liệu của file và thuật toán nén. Nó thường được sử dụng để nén các file và thư mục.

Package java.util.zip cung cấp các lớp để thực thi việc ZIP file trong java.

ZIP một file duy nhất

File: ZIPFileExample.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69      

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

 

public class ZIPFileExample1 {

    /**

     * main

     *

     * @param args

     * @throws IOException

     */

    public static void main(String[] args) throws IOException {

        final File inputFile = new File("D:\temp\ziptest.txt");

        final String zipFilePath = "D:\temp\ziptest.zip";

        zipFile(inputFile, zipFilePath);

    }

 

    /**

     * zip file

     *

     * @param inputFile

     * @param zipFilePath

     * @throws IOException

     */

    private static void zipFile(File inputFile, String zipFilePath)

            throws IOException {

        FileInputStream fis = null;

        FileOutputStream fos = null;

        ZipOutputStream zipos = null;

 

        try {

            fos = new FileOutputStream(zipFilePath);

            zipos = new ZipOutputStream(fos);

 

            ZipEntry zipEntry = new ZipEntry(inputFile.getName());

            zipos.putNextEntry(zipEntry);

 

            fis = new FileInputStream(inputFile);

            byte[] buf = new byte[1024];

            int length;

            while ((length = fis.read(buf)) > 0) {

                zipos.write(buf, 0, length);

            }

            System.out.println("File " + inputFile

                    + " da duoc zip thanh file " + zipFilePath);

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (zipos != null) {

                // close ZipEntry

                zipos.closeEntry();

                // close ZipOutputStream

                zipos.close();

            }

            // close FileOutputStream

            if (fos != null)

                fos.close();

            // close FileInputStream

            if (fis != null)

                fis.close();

        }

    }

}

Output:

 File D:	empziptest.txt da duoc zip thanh file D:	empziptest.zip

Nguồn tin: viettuts.vn