Nén file theo format mong muốn trong java

Trong bài viết hướng dẫn này, tôi sẽ hướng dẫn các bạn tìm hiểu cách nén các tệp ở định dạng ZIP, hoặc các format khác bằng gói java.util.zip. Trong java, có các lớp nằm trong gói java.util.zip giúp bạn giải quyết nhanh chóng vấn đề nén và giải nén file.

1. Các bước để nén một tệp trong Java

Các bạn hãy hình dung và xem đoạn code bên dưới để thực hiện:

public static void zipFile() throws IOException {
		// note 1
		final String fileName = "file1.txt";
		final String dirPath = "filezips";
		
		// note 2
		File dir = new File(dirPath);
		if (!dir.exists()) {
			dir.mkdir();
		}
		// note 3
		String filePath = dirPath + File.separator + fileName;
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		
		// note 4
		String zipFileName = file.getName().concat(".zip");

		FileOutputStream fosW = null;
		FileOutputStream fos = null;
		Scanner input = null;
		ZipOutputStream zos = null;
		try {
			fosW = new FileOutputStream(zipFileName);
			fos = new FileOutputStream(file);
			input = new Scanner(System.in);
			System.out.println("Please enter string :");
			String strUser = input.nextLine();
			fos.write(strUser.getBytes());
			
			zos = new ZipOutputStream(fosW);
			zos.putNextEntry(new ZipEntry(file.getName()));
			byte[] bytes = Files.readAllBytes(Paths.get(filePath));
			zos.write(bytes);
			zos.closeEntry();
			zos.finish();
		} catch (Exception e) {
			System.out.println("Error when zip file!");
		} finally {
			zos.close();
			fosW.close();
			input.close();
			fos.close();
		}
	}

2. Giải thích những đoạn code trên

Ở dòng đầu tiên // note 1, các bạn thấy rằng đó là các bước để thực hiện tạo ra các đường dẫn chưa file, tạo tên file.

final String fileName = "file1.txt";
final String dirPath = "filezips";

Ở dòng note 2 kiểm tra xem nếu thư mục chưa tồn tại sẽ tạo ra thư mục có tên đã tạo.

File dir = new File(dirPath);
if (!dir.exists()) {
	dir.mkdir();
}

Tiếp theo kiểm tra xem nếu chưa tồn tại file, thì sẽ tạo ra file có tên đã khai báo:

String filePath = dirPath + File.separator + fileName;
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
String zipFileName = file.getName().concat(".zip");

Dòng trên để tạo đuôi file cần nén

fosW = new FileOutputStream(zipFileName);

Tạo đối tượng FileOutputStream mục đích dùng để ghi nội dung vào file.

fos = new FileOutputStream(file);

Tạo đối tượng FileOutputStream mục đích cần có đề nén file

input = new Scanner(System.in);
System.out.println("Please enter string :");
String strUser = input.nextLine();

Dòng trên dùng để nhập thông tin từ bàn phím, ta dùng Scanner trong java, một lớp quá quen thuộc.

Tiếp tục ta tiến hành ghi nội dung vừa nhập vào đối tượng FileOutputStream

fos.write(strUser.getBytes());

Đoạn code bên dưới này dùng để lấy tất cả nôi dung của file cần nén và sau đó nén tệp lại.

zos = new ZipOutputStream(fosW);
zos.putNextEntry(new ZipEntry(file.getName()));
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
zos.write(bytes);
zos.finish();

Sau khi xử lý xong, cần đóng lại các kết nối đề giải phóng tài nguyên.

zos.closeEntry();
zos.close();
fosW.close();
input.close();
fos.close();

Hình ảnh bên dưới chính là output:

 

Trên là hướng dẫn cách Nén file theo format mong muốn trong java, chúc các bạn học tốt!

 

 

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận
x