溫馨提示×

java unzip能否加密文件

小樊
130
2024-07-20 19:00:06
欄目: 編程語言

是的,Java中可以使用密碼來加密和解密ZIP文件??梢允褂?code>ZipEntry.setCrc方法設置密碼,以確保只有知道密碼的用戶才能解壓縮文件。以下是一個簡單的示例代碼:

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

public class UnzipWithPassword {
    public static void main(String[] args) {
        String zipFilePath = "encrypted.zip";
        String destDir = "unzipped";
        String password = "mypassword";

        try {
            byte[] buffer = new byte[1024];

            ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
            ZipEntry zipEntry = zis.getNextEntry();

            while (zipEntry != null) {
                String fileName = zipEntry.getName();
                FileOutputStream fos = new FileOutputStream(destDir + "/" + fileName);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                zipEntry = zis.getNextEntry();
            }

            zis.closeEntry();
            zis.close();

            System.out.println("File unzipped successfully");
        } catch (Exception e) {
            System.out.println("Error unzipping file: " + e.getMessage());
        }
    }
}

在上面的示例中,我們通過ZipInputStream讀取ZIP文件中的內容,然后逐個解壓縮文件。要使用加密ZIP文件,您需要在解壓縮文件之前設置密碼。這可以通過將密碼傳遞給ZipInputStream的構造函數來實現。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女