GP Coder

Trang chia sẻ kiến thức lập trình Java

  • Java Core
    • Basic Java
    • OOP
    • Exception Handling
    • Multi-Thread
    • Java I/O
    • Networking
    • Reflection
    • Collection
    • Java 8
  • Design pattern
    • Creational Pattern
    • Structuaral Pattern
    • Behavior Pattern
  • Web Service
    • SOAP
    • REST
  • JPA
  • Java library
    • Report
    • Json
    • Unit Test
  • Message Queue
    • ActiveMQ
    • RabbitMQ
  • All
Trang chủ Java Core Java I/O Hướng dẫn nén và giải nén trong java

Hướng dẫn nén và giải nén trong java

Đăng vào 19/12/2017 . Được đăng bởi GP Coder . 12425 Lượt xem . Toàn màn hình

Để xử lý các công việc liên quan tới nén và giải nén, JDK cung cấp 2 package:

  • java.util.zip cung cấp các lớp hỗ trợ đọc và thi file .zip.
  • java.util.jar cung cấp các lớp hỗ trợ đọc và thi file .jar.

Các định dạng nén khác như: .rar, .7zip, … cần sử dụng một thư viện khác hỗ trợ.

Nội dung

  • 1 Đọc ghi file zip sử dụng java.util.zip
  • 2 Đọc ghi file zip sử dụng thư viện zip4j
  • 3 Đọc ghi file jar sử dụng java.util.jar
  • 4 Đọc và ghi file rar

Đọc ghi file zip sử dụng java.util.zip

java.util.zip coi các file/folder trong file zip là các ZipEntry. Một folder cũng là một ZipEntry.

Hãy xem nội dung file nén như sau:

Ví dụ nén file zip

Thực hiện các bước như sau:

  • Đọc file sử dụng FileInputStream.
  • Thêm tên file vào “ZipEntry“.
  • Xuất ra file “ZipOutputStream“.

package com.gpcoder.compress;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileExample {
	public static void main(String[] args) throws IOException {
		byte[] buffer = new byte[1024];

		OutputStream fos = new FileOutputStream("C:/demo/demo.zip");
		ZipOutputStream zos = new ZipOutputStream(fos);
		ZipEntry ze = new ZipEntry("sql.log"); // file name
		zos.putNextEntry(ze);
		
		FileInputStream in = new FileInputStream("C:/demo/data/sql.log");
		int len;
		while ((len = in.read(buffer)) > 0) {
			zos.write(buffer, 0, len);
		}
		in.close();
		
		zos.closeEntry();
		zos.close(); // remember close it
		System.out.println("Done");
	}
}

Thực thi chương trình trên, một file demo.zip được tạo ra trong thư mục C:/demo

Ví dụ nén thư mục


package com.gpcoder.compress;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipDirectoryExample {

	public static final String OUTPUT_ZIP_FILE = "C:/demo/demo.zip";
	public static final String SOURCE_FOLDER = "C:/demo/data";
	public static final byte[] BUFFER = new byte[1024];

	public static void main(String[] args) {
        File outputZipFile = new File(OUTPUT_ZIP_FILE);
		File inputDir = new File(SOURCE_FOLDER);
		zipDirectory(inputDir, outputZipFile);
	}

	/**
	 * Nén tất cả các tập tin và thư mục trong thư mục đầu vào
	 * @param inputDir Thư mục đầu vào
	 * @param outputZipFile Tập tin đầu ra
	 */
	public static void zipDirectory(File inputDir, File outputZipFile) {
        // Tạo thư mục cha cho file đầu ra (output file).
        outputZipFile.getParentFile().mkdirs();
 
        String inputDirPath = inputDir.getAbsolutePath();
 
        FileOutputStream fos = null;
        ZipOutputStream zipOs = null;
        try {
 
            List<File> allFiles = listChildFiles(inputDir);
 
            // Tạo đối tượng ZipOutputStream để ghi file zip.
            fos = new FileOutputStream(outputZipFile);
            zipOs = new ZipOutputStream(fos);
            for (File file : allFiles) {
                String filePath = file.getAbsolutePath();
 
                System.out.println("Zipping " + filePath);
                // entryName: is a relative path.
                String entryName = filePath.substring(inputDirPath.length() + 1);
 
                ZipEntry ze = new ZipEntry(entryName);
                // Thêm entry vào file zip.
                zipOs.putNextEntry(ze);
                // Đọc dữ liệu của file và ghi vào ZipOutputStream.
                FileInputStream fileIs = new FileInputStream(filePath);
 
                int len;
                while ((len = fileIs.read(BUFFER)) > 0) {
                    zipOs.write(BUFFER, 0, len);
                }
                fileIs.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	closeStream(zipOs);
        	closeStream(fos);
        }
 
    }

	private static void closeStream(OutputStream out) {
        try {
            out.close();
        } catch (Exception ex) {
        	ex.printStackTrace();
        }
    }
	
	/**
	 * Lấy danh sách các file trong thư mục: 
	 * 		bao gồm tất cả các file con, cháu,.. của thư mục đầu vào.
	 */
    private static List<File> listChildFiles(File dir) throws IOException {
        List<File> allFiles = new ArrayList<>();
 
        File[] childFiles = dir.listFiles();
        for (File file : childFiles) {
            if (file.isFile()) {
                allFiles.add(file);
            } else {
                List<File> files = listChildFiles(file);
                allFiles.addAll(files);
            }
        }
        return allFiles;
    }

}

Thực thi chương trình trên, một file demo.zip được tạo ra trong thư mục C:/demo

Ví dụ liệt kê các file/folder trong file zip


package com.gpcoder.compress;

import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ReadZipFileExample {

	public static final String ZIP_FILE = "C:/demo/demo.zip";

	public static void main(String[] args) {
		ZipInputStream zis = null;
		try {
			// Tạo đối tượng ZipInputStream để đọc file zip.
			zis = new ZipInputStream(new FileInputStream(ZIP_FILE));

			ZipEntry entry = null;
			while ((entry = zis.getNextEntry()) != null) {
				if (entry.isDirectory()) {
					System.out.print("Directory: ");
				} else {
					System.out.print("File: ");
				}
				System.out.println(entry.getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				zis.close();
			} catch (Exception e) {
			}
		}
	}
}

Kết quả thực thi chương trình trên:


File: docs\test1.txt
File: docs\test2.txt
File: javaInterviewQuestions.docx
File: note.txt
File: sql.log
File: table.xlsx

Ví dụ giải nén file zip


package com.gpcoder.compress;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZipFileExample {

	public static final String ZIP_FILE = "C:\\demo\\demo.zip";
	public static final String OUTPUT_FOLDER = "C:\\demo\\output";
	public static final byte[] BUFFER = new byte[1024];

	public static void main(String[] args) {
		// Tạo thư mục Output nếu không tồn tại
		File folder = new File(OUTPUT_FOLDER);
		if (!folder.exists()) {
			folder.mkdirs();
		}

		ZipInputStream zis = null;
		try {
			zis = new ZipInputStream(new FileInputStream(ZIP_FILE));

			ZipEntry entry;
			File file;
			OutputStream os;
			String entryName;
			String outFileName;
			while ((entry = zis.getNextEntry()) != null) {
				entryName = entry.getName();
				outFileName = OUTPUT_FOLDER + File.separator + entryName;
				System.out.println("Unzip: " + outFileName);

				file = new File(outFileName);
				if (entry.isDirectory()) {
					// Tạo các thư mục.
					file.mkdirs();
				} else {
					// Tạo các thư mục nếu không tồn tại
					if (!file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					// Tạo một Stream để ghi dữ liệu vào file.
					os = new FileOutputStream(outFileName);
					int len;
					while ((len = zis.read(BUFFER)) > 0) {
						os.write(BUFFER, 0, len);
					}
					os.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				zis.close();
			} catch (Exception e) {
			}
		}
	}
}

Thực thi chương trình trên, các file/ folder trong file zip được giải nén trong thư mục C:/demo/output, console của eclipse hiển thị kết quả như sau:


Unzip: C:\demo\output\docs\test1.txt
Unzip: C:\demo\output\docs\test2.txt
Unzip: C:\demo\output\javaInterviewQuestions.docx
Unzip: C:\demo\output\note.txt
Unzip: C:\demo\output\sql.log
Unzip: C:\demo\output\table.xlsx

Ví dụ nén file zip với checksum


package com.gpcoder.compress.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipWithChecksum {

	public static final String OUTPUT_ZIP_FILE = "C:/demo/data-checksum.zip";
	public static final String SOURCE_FOLDER = "C:/demo/data";
	public static final byte[] BUFFER = new byte[1024];

	public static void main(String[] args) {
		File outputZipFile = new File(OUTPUT_ZIP_FILE);
		File inputDir = new File(SOURCE_FOLDER);
		zipDirectory(inputDir, outputZipFile);
	}

	/**
	 * Nén tất cả các tập tin và thư mục trong thư mục đầu vào
	 * 
	 * @param inputDir Thư mục đầu vào
	 * @param outputZipFile Tập tin đầu ra
	 */
	public static void zipDirectory(File inputDir, File outputZipFile) {
		// Tạo thư mục cha cho file đầu ra (output file).
		outputZipFile.getParentFile().mkdirs();

		String inputDirPath = inputDir.getAbsolutePath();

		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		CheckedOutputStream checksum = null;
		try {

			List<File> allFiles = listChildFiles(inputDir);

			// Tạo đối tượng ZipOutputStream để ghi file zip.
			fos = new FileOutputStream(outputZipFile);

			// An output stream that also maintains a checksum of the data being
			// written. The checksum can then be used to verify the integrity of
			// the output data.
			checksum = new CheckedOutputStream(fos, new Adler32());
			zos = new ZipOutputStream(new BufferedOutputStream(checksum));

			for (File file : allFiles) {
				String filePath = file.getAbsolutePath();

				System.out.println("Zipping " + filePath);
				// entryName: is a relative path.
				String entryName = filePath.substring(inputDirPath.length() + 1);

				ZipEntry ze = new ZipEntry(entryName);
				// Thêm entry vào file zip.
				zos.putNextEntry(ze);
				// Đọc dữ liệu của file và ghi vào ZipOutputStream.
				FileInputStream fileIs = new FileInputStream(filePath);
				BufferedInputStream bis = new BufferedInputStream(fileIs, BUFFER.length);

				// read data to the end of the source file and write it to the zip
				// output stream.
				int length;
				while ((length = bis.read(BUFFER, 0, BUFFER.length)) > 0) {
					zos.write(BUFFER, 0, length);
				}
				fileIs.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeStream(zos);
			closeStream(fos);
		}

		// Print out checksum value
		if (checksum != null) {
			System.out.println("Checksum   : " + checksum.getChecksum().getValue());
		}

	}

	private static void closeStream(OutputStream out) {
		try {
			out.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Lấy danh sách các file trong thư mục: bao gồm tất cả các file con, cháu,..
	 * của thư mục đầu vào.
	 */
	private static List<File> listChildFiles(File dir) throws IOException {
		List<File> allFiles = new ArrayList<>();

		File[] childFiles = dir.listFiles();
		for (File file : childFiles) {
			if (file.isFile()) {
				allFiles.add(file);
			} else {
				List<File> files = listChildFiles(file);
				allFiles.addAll(files);
			}
		}
		return allFiles;
	}
}

Kết quả thực thi chương trình trên:


Zipping C:\demo\data\docs\test1.txt
Zipping C:\demo\data\docs\test2.txt
Zipping C:\demo\data\javaInterviewQuestions.docx
Zipping C:\demo\data\note.txt
Zipping C:\demo\data\sql.log
Zipping C:\demo\data\table.xlsx
Checksum   : 320788343

Ví dụ giải nén với checksum


package com.gpcoder.compress.zip;

import java.io.*;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.CheckedInputStream;
import java.util.zip.Adler32;

public class UnzipWithChecksum {

	public static final String ZIP_FILE = "C:/demo/data-checksum.zip";
	public static final String OUTPUT_FOLDER = "C:/demo/data-checksum";
	public static final byte[] BUFFER = new byte[1024];

	public static void main(String[] args) {

		// Tạo thư mục Output nếu không tồn tại
		File folder = new File(OUTPUT_FOLDER);
		if (!folder.exists()) {
			folder.mkdirs();
		}

		FileInputStream fis = null;
		ZipInputStream zis = null;
		CheckedInputStream checksum = null;
		try {
			fis = new FileInputStream(ZIP_FILE);

			// Creating input stream that also maintains the checksum of the
			// data which later can be used to validate data integrity.
			checksum = new CheckedInputStream(fis, new Adler32());
			zis = new ZipInputStream(new BufferedInputStream(checksum));

			// Read each entry from the ZipInputStream until no more entry found
			// indicated by a null return value of the getNextEntry() method.
			ZipEntry entry;
			File file;
			OutputStream os;
			String entryName;
			String outFileName;
			while ((entry = zis.getNextEntry()) != null) {
				entryName = entry.getName();
				outFileName = OUTPUT_FOLDER + File.separator + entryName;
				System.out.println("Unzip: " + outFileName);

				file = new File(outFileName);
				if (entry.isDirectory()) {
					// Tạo các thư mục.
					file.mkdirs();
				} else {
					// Tạo các thư mục nếu không tồn tại
					if (!file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					// Tạo một Stream để ghi dữ liệu vào file.
					os = new FileOutputStream(outFileName);
					int len;
					while ((len = zis.read(BUFFER)) > 0) {
						os.write(BUFFER, 0, len);
					}
					os.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				zis.close();
			} catch (Exception e) {
			}
			try {
				zis.close();
			} catch (Exception e) {
			}
		}

		// Print out the checksum value
		if (checksum != null) {
			System.out.println("Checksum = " + checksum.getChecksum().getValue());
		}
	}
}

Kết quả thực thi chương trình trên:


Unzip: C:/demo/data-checksum\docs\test1.txt
Unzip: C:/demo/data-checksum\docs\test2.txt
Unzip: C:/demo/data-checksum\javaInterviewQuestions.docx
Unzip: C:/demo/data-checksum\note.txt
Unzip: C:/demo/data-checksum\sql.log
Unzip: C:/demo/data-checksum\table.xlsx
Checksum = 320788343

Ví dụ nén dữ liệu với gzip

User.java


package com.gpcoder.compress.gzip;

import java.io.Serializable;

public class User implements Serializable {

	private static final long serialVersionUID = -657143570052942947L;

	private Long id;
	private String username;
	private String password;
	private String firstName;
	private String lastName;

	@Override
	public String toString() {
		return "User [id=" + id 
				+ ", username=" + username 
				+ ", password=" + password 
				+ ", firstName=" + firstName
				+ ", lastName=" + lastName + "]";
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}

GZipObjectDemo.java


package com.gpcoder.compress.gzip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPOutputStream;

public class GZipObjectDemo {
	public static String OUTPUT_FILE = "C:/demo/user.dat";
	
    public static void main(String[] args) {
        User admin = new User();
        admin.setId(1L);
        admin.setUsername("admin");
        admin.setPassword("secret");
        admin.setFirstName("System");
        admin.setLastName("Administrator");

        User foo = new User();
        foo.setId(2L);
        foo.setUsername("foo");
        foo.setPassword("secret");
        foo.setFirstName("Foo");
        foo.setLastName("Bar");

        System.out.println("Zipping....");
        System.out.println(admin);
        System.out.println(foo);
        try {
            FileOutputStream fos = new FileOutputStream(new File(OUTPUT_FILE));
            GZIPOutputStream gos = new GZIPOutputStream(fos);
            ObjectOutputStream oos = new ObjectOutputStream(gos);

            oos.writeObject(admin);
            oos.writeObject(foo);

            oos.flush();
            oos.close();

            gos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Thực thi chương trình trên, một file user.dat được tạo ra trong thư mục C:/demo

Ví dụ giải nén dữ liệu với gzip


package com.gpcoder.compress.gzip;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.zip.GZIPInputStream;

public class UnGZipObjectDemo {
	
	public static String OUTPUT_FILE = "C:/demo/user.dat";
	
    public static void main(String[] args) {
        User admin = null;
        User foo = null;

        try {
            FileInputStream fis = new FileInputStream(new File(OUTPUT_FILE));
            GZIPInputStream gis = new GZIPInputStream(fis);
            ObjectInputStream ois = new ObjectInputStream(gis);

            admin = (User) ois.readObject();
            foo = (User) ois.readObject();

            ois.close();
            gis.close();
            fis.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println(admin);
        System.out.println(foo);
    }
}

Kết quả thực thi chương trình trên:


User [id=1, username=admin, password=secret, firstName=System, lastName=Administrator]
User [id=2, username=foo, password=secret, firstName=Foo, lastName=Bar]

Ví dụ nén file gzip


package com.gpcoder.compress.gzip;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class GZipCompressExample {

	public static final String OUTPUT_FILE = "C:/demo/gzip-output.gz";
	public static final String INPUT_FILE = "C:/demo/data/note.txt";
	public static final byte[] BUFFER = new byte[1024];

	public static void main(String[] args) throws IOException {
		// Create a file output stream the write the gzip result into
		// a specified file name.
		FileOutputStream fos = new FileOutputStream(OUTPUT_FILE);

		// Create a gzip output stream object with file output stream
		// as the argument.
		GZIPOutputStream gzos = new GZIPOutputStream(fos);

		// Create a file input stream of the file that is going to be
		// compressed.
		FileInputStream fis = new FileInputStream(INPUT_FILE);

		// Read all the content of the file input stream and write it
		// to the gzip output stream object.
		int length;
		while ((length = fis.read(BUFFER)) > 0) {
			gzos.write(BUFFER, 0, length);
		}

		// Finish file compressing and close all streams.
		fis.close();
		gzos.finish();
		gzos.close();
		System.out.println("Done!!!");
	}
}

Thực thi chương trình trên, một file gzip-output.gz được tạo ra trong thư mục C:/demo

Ví dụ giải nén file gzip


package com.gpcoder.compress.gzip;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

public class GZipDecompressExample {

	public static final String INPUT_FILE = "C:/demo/gzip-output.gz";
	public static final String OUTPUT_FILE = "C:/demo/note.txt";
	public static final byte[] BUFFER = new byte[1024];

	public static void main(String[] args) throws IOException {
		// Create a file input stream to read the source file.
		FileInputStream fis = new FileInputStream(INPUT_FILE);

		// Create a gzip input stream to decompress the source
		// file defined by the file input stream.
		GZIPInputStream gzis = new GZIPInputStream(fis);

		// Create file output stream where the decompress result
		// will be stored.
		FileOutputStream fos = new FileOutputStream(OUTPUT_FILE);

		// Read from the compressed source file and write the
		// decompress file.
		int length;
		while ((length = gzis.read(BUFFER)) > 0) {
			fos.write(BUFFER, 0, length);
		}

		// Close the resources.
		fos.close();
		gzis.close();
		fis.close();
		System.out.println("Done!!!");
	}
}

Thực thi chương trình trên, một file note.txt được giải nén trong thư mục C:/demo

Đọc ghi file zip sử dụng thư viện zip4j

Download thư viện zip4j: thêm khai báo thư viện maven vào project.


<!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j -->
<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>1.3.2</version>
</dependency>

Ví dụ nén file zip với Password


package com.gpcoder.compress;

import java.io.File;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

public class Zip4jExample {

	public static final String OUTPUT_ZIP_FILE = "C:/demo/zip4jFolderExample.zip";
	public static final String SOURCE_FOLDER = "C:/demo/data";
	public static final String PASSWORD = "yourPassword";

	public static void main(String[] args) throws ZipException {
		ZipParameters parameters = new ZipParameters();
		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
		parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

		if (PASSWORD.length() > 0) {
			parameters.setEncryptFiles(true);
			parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
			parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
			parameters.setPassword(PASSWORD);
		}

		// Zip files inside a folder
		// An exception will be thrown if the output file already exists
		File outputFile = new File(OUTPUT_ZIP_FILE);
		ZipFile zipFile = new ZipFile(outputFile);

		File sourceFolder = new File(SOURCE_FOLDER);
		// false - indicates archive should not be split and 0 is split length
		zipFile.createZipFileFromFolder(sourceFolder, parameters, false, 0);

		// Zip a single file
		// An exception will be thrown if the output file already exists
		outputFile = new File("C:/demo/zip4jFileExample.zip");
		zipFile = new ZipFile(outputFile);
		File sourceFile = new File("C:/demo/data/sql.log");
		zipFile.addFile(sourceFile, parameters);
		System.out.println("Done!!!");
	}
}

Thực thi chương trình trên, 2 file zip4jFolderExample.zip và zip4jFileExample.zip được tạo ra trong thư mục C:/demo

Ví dụ giải nén file zip có Password


package com.gpcoder.compress;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;

public class UnZip4jExample {

	public static final String ZIP_FILE = "C:/demo/zip4jFolderExample.zip";
	public static final String DESTINATION_FOLDER = "C:/demo/outputZip4j";
	public static final String PASSWORD = "yourPassword";
	
	public static void main(String[] args) throws ZipException {
		ZipFile zipFile = new ZipFile(ZIP_FILE);
		if (zipFile.isEncrypted()) {
			zipFile.setPassword(PASSWORD);
		}
		zipFile.extractAll(DESTINATION_FOLDER);
		System.out.println("Done!!!");
	}
}

Thực thi chương trình trên, nội dung file zip được giải nén trong thư mục C:/demo/outputZip4j

Đọc ghi file jar sử dụng java.util.jar

Về cơ bản việc đọc ghi file .jar không có gì khác biệt so với file .zip.

  • JarInputStream mở rộng từ ZipInputStream hỗ trợ thêm tính năng đọc các thông tin MANIFEST.
  • JarOutputStream mở rộng từ ZipOutputStream hỗ trợ thêm tính năng ghi thông tin MANIFEST.

Các file thư viện .jar thông thường của java thường có thông tin MANIFEST rất đơn giản.

Các file/ folder trong file .jar được coi là các JarEntry.

Ghi file jar


package com.gpcoder.compress;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

public class CreateJarFileExample {

	public static final String JAR_FILE = "C:/demo/gpcoder.jar";
	public static final String INPUT_FOLDER = "C:/demo/classes";
	public static final byte[] BUFFER = new byte[1024];

	public static void main(String[] args) throws IOException {
		File outputZipFile = new File(JAR_FILE);
		File inputDir = new File(INPUT_FOLDER);
		createJarFile(inputDir, outputZipFile);
	}

	/**
	 * Nén tất cả các tập tin và thư mục trong thư mục đầu vào 
	 * 
	 * @param inputDirThư mục đầu vào
	 * @param outputJarFile Tập tin đầu ra
	 */
	public static void createJarFile(File inputDir, File outputJarFile) {
		// Tạo thư mục cha cho file đầu ra (output file).
		outputJarFile.getParentFile().mkdirs();
		String inputDirPath = inputDir.getAbsolutePath();

		// prepare Manifest file
		String version = "1.0.0";
		String author = "gpcoder.com";
		Manifest manifest = new Manifest();
		Attributes global = manifest.getMainAttributes();
		global.put(Attributes.Name.MANIFEST_VERSION, version);
		global.put(new Attributes.Name("Created-By"), author);

		FileOutputStream fos = null;
		JarOutputStream jos = null;
		try {

			List<File> allFiles = listChildFiles(inputDir);

			// Tạo đối tượng JarOutputStream để ghi file jar.
			fos = new FileOutputStream(outputJarFile);
			jos = new JarOutputStream(fos, manifest);
			for (File file : allFiles) {
				String filePath = file.getAbsolutePath();

				System.out.println("Creating jar: " + filePath);
				// entryName: is a relative path.
				String entryName = filePath.substring(inputDirPath.length() + 1);

				// create JarEntry
				JarEntry je = new JarEntry(entryName);
				je.setComment("Creating Jar");
				je.setTime(Calendar.getInstance().getTimeInMillis());
				// Thêm entry vào file jar.
				jos.putNextEntry(je);

				// Đọc dữ liệu của file và ghi vào JarOutputStream.
				InputStream fileIs = new FileInputStream(filePath);
				int len;
				while ((len = fileIs.read(BUFFER)) > 0) {
					jos.write(BUFFER, 0, len);
				}
				fileIs.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeStream(jos);
			closeStream(fos);
		}

	}

	private static void closeStream(OutputStream out) {
		try {
			out.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Lấy danh sách các file trong thư mục: 
	 * 		bao gồm tất cả các file con, cháu,.. của thư mục đầu vào.
	 */
	private static List<File> listChildFiles(File dir) throws IOException {
		List<File> allFiles = new ArrayList<>();

		File[] childFiles = dir.listFiles();
		for (File file : childFiles) {
			if (file.isFile()) {
				allFiles.add(file);
			} else {
				List<File> files = listChildFiles(file);
				allFiles.addAll(files);
			}
		}
		return allFiles;
	}

}

Thực thi chương trình trên, một file gpcoder.jar được tạo ra trong thư mục C:/demo và console của eclipse hiển thị như sau:


Creating jar: C:\demo\classes\com\gpcoder\AbsoluteRelavativePathExample.class
Creating jar: C:\demo\classes\com\gpcoder\compress\CreateJarFileExample.class
Creating jar: C:\demo\classes\com\gpcoder\compress\ReadZipFileExample.class
Creating jar: C:\demo\classes\com\gpcoder\compress\UnZipFileExample.class
Creating jar: C:\demo\classes\com\gpcoder\compress\ZipDirectoryExample.class
Creating jar: C:\demo\classes\com\gpcoder\compress\ZipFileExample.class
Creating jar: C:\demo\classes\com\gpcoder\DeleteFileExample.class
Creating jar: C:\demo\classes\com\gpcoder\DeleteFolderExample.class
Creating jar: C:\demo\classes\com\gpcoder\TxtFileFilter.class
Creating jar: C:\demo\classes\com\gpcoder\TxtFileNameFilter.class

Đọc nội dung file jar


package com.gpcoder.compress;

import java.io.FileInputStream;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;

public class ReadJarFileExample {

	public static final String JAR_FILE = "C:/demo/gpcoder.jar";

	public static void main(String[] args) {
		JarInputStream zis = null;
		try {
			// Tạo đối tượng JarInputStream để đọc file jar.
			zis = new JarInputStream(new FileInputStream(JAR_FILE));

			// Đọc thông tin Manifest:
			Manifest manifest = zis.getManifest();
			Attributes atts = manifest.getMainAttributes();
			String version = atts.getValue("Manifest-Version");
			String createdBy = atts.getValue("Created-By");
			System.out.println("Manifest-Version:" + version);
			System.out.println("Created-By:" + createdBy);

			JarEntry entry = null;
			while ((entry = zis.getNextJarEntry()) != null) {
				if (entry.isDirectory()) {
					System.out.print("Folder: ");
				} else {
					System.out.print("File: ");
				}
				System.out.println(entry.getName());
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				zis.close();
			} catch (Exception e) {
			}
		}
	}

}

Kết quả thực thi chương trình trên:


Manifest-Version:1.0.0
Created-By:gpcoder.com
File: com\gpcoder\AbsoluteRelavativePathExample.class
File: com\gpcoder\compress\CreateJarFileExample.class
File: com\gpcoder\compress\ReadZipFileExample.class
File: com\gpcoder\compress\UnZipFileExample.class
File: com\gpcoder\compress\ZipDirectoryExample.class
File: com\gpcoder\compress\ZipFileExample.class
File: com\gpcoder\DeleteFileExample.class
File: com\gpcoder\DeleteFolderExample.class
File: com\gpcoder\TxtFileFilter.class
File: com\gpcoder\TxtFileNameFilter.class

Đọc và ghi file rar

Để xử lý file .rar cần một thư viện mã nguồn mở, có thể sử dụng một trong các thư viện sau: JUnRar, java-unrar. Các ví dụ sử dụng các bạn xem trên source code của thư viện:

  • JUnRar: https://github.com/edmund-wagner/junrar
  • java-unrar: https://github.com/jukka/java-unrar
5.0
07
Nếu bạn thấy hay thì hãy chia sẻ bài viết cho mọi người nhé! Và Donate tác giả

Shares

Chuyên mục: Java I/O Được gắn thẻ: IO, zip

Đọc ghi file CSV trong Java
Hướng dẫn đọc và ghi file excel trong Java sử dụng thư viện Apache POI

Có thể bạn muốn xem:

  • Hướng dẫn sử dụng luồng vào ra nhị phân trong Java (12/12/2017)
  • Hướng dẫn sử dụng luồng vào ra ký tự trong Java (13/12/2017)
  • Hướng dẫn phân tích nội dung HTML sử dụng thư viện Jsoup (02/01/2018)
  • Giới thiệu luồng vào ra (I/O) trong Java (11/12/2017)
  • Hướng dẫn sử dụng lớp Console trong java (15/12/2017)

Bình luận

bình luận

Tìm kiếm

Bài viết mới

  • Clean code 13/01/2024
  • Giới thiệu CloudAMQP – Một RabbitMQ server trên Cloud 02/10/2020
  • Kết nối RabbitMQ sử dụng Web STOMP Plugin 19/06/2020
  • Sử dụng publisher confirm trong RabbitMQ 16/06/2020
  • Sử dụng Dead Letter Exchange trong RabbitMQ 13/06/2020

Xem nhiều

  • Hướng dẫn Java Design Pattern – Factory Method (98061 lượt xem)
  • Hướng dẫn Java Design Pattern – Singleton (97702 lượt xem)
  • Giới thiệu Design Patterns (87769 lượt xem)
  • Lập trình đa luồng trong Java (Java Multi-threading) (86441 lượt xem)
  • Giới thiệu về Stream API trong Java 8 (83840 lượt xem)

Nội dung bài viết

  • 1 Đọc ghi file zip sử dụng java.util.zip
  • 2 Đọc ghi file zip sử dụng thư viện zip4j
  • 3 Đọc ghi file jar sử dụng java.util.jar
  • 4 Đọc và ghi file rar

Lưu trữ

Thẻ đánh dấu

Annotation Authentication Basic Java Behavior Pattern Collection Creational Design Pattern Cấu trúc điều khiển Database Dependency Injection Design pattern Eclipse Exception Executor Service Google Guice Gson Hibernate How to Interceptor IO Jackson Java 8 Java Core JDBC JDK Jersey JMS JPA json JUnit JWT Message Queue Mockito Multithreading OOP PowerMockito RabbitMQ Reflection Report REST SOAP Structuaral Pattern Swagger Thread Pool Unit Test Webservice

Liên kết

  • Clean Code
  • JavaTpoint
  • Refactoring Guru
  • Source Making
  • TutorialsPoint
  • W3Schools Online Web Tutorials

Giới thiệu

GP Coder là trang web cá nhân, được thành lập với mục đích lưu trữ, chia sẽ kiến thức đã học và làm việc của tôi. Các bài viết trên trang này chủ yếu về ngôn ngữ Java và các công nghệ có liên quan đến Java như: Spring, JSF, Web Services, Unit Test, Hibernate, SQL, ...
Hi vọng góp được chút ít công sức cho sự phát triển cộng đồng Coder Việt.

Donate tác giả

Tìm kiếm các bài viết của GP Coder với Google Search

Liên hệ

Các bạn có thể liên hệ với tôi thông qua:
  • Trang liên hệ
  • Linkedin: gpcoder
  • Email: contact@gpcoder.com
  • Skype: ptgiang56it

Follow me

Copyright 2025 © GP Coder · All Rights Reserved · Giới thiệu · Chính sách · Điều khoản · Liên hệ ·

Share

Blogger
Delicious
Digg
Email
Facebook
Facebook messenger
Flipboard
Google
Hacker News
Line
LinkedIn
Mastodon
Mix
Odnoklassniki
PDF
Pinterest
Pocket
Print
Reddit
Renren
Short link
SMS
Skype
Telegram
Tumblr
Twitter
VKontakte
wechat
Weibo
WhatsApp
X
Xing
Yahoo! Mail

Copy short link

Copy link