java unzip怎么與腳本結(jié)合

小樊
82
2024-07-20 19:02:58
欄目: 編程語言

您可以使用Java中的java.util.zip包來解壓文件,并通過運(yùn)行腳本來實(shí)現(xiàn)與腳本的結(jié)合。以下是一個(gè)簡單的例子來展示如何在Java程序中解壓文件并與腳本結(jié)合:

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

public class UnzipExample {

    public static void main(String[] args) {
        String zipFilePath = "path/to/your/zip/file.zip";
        String destDir = "path/to/your/destination/directory";

        unzip(zipFilePath, destDir);

        // Run your script here
        Runtime rt = Runtime.getRuntime();
        try {
            Process pr = rt.exec("path/to/your/script.sh");
            pr.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void unzip(String zipFilePath, String destDir) {
        byte[] buffer = new byte[1024];

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

            while (zipEntry != null) {
                String fileName = zipEntry.getName();
                File newFile = new File(destDir + File.separator + fileName);

                if (zipEntry.isDirectory()) {
                    new File(newFile.getParent()).mkdirs();
                } else {
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }

                zipEntry = zis.getNextEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的例子中,unzip方法用于解壓文件,然后在main方法中解壓zip文件并運(yùn)行您的腳本。您需要將path/to/your/zip/file.zippath/to/your/destination/directory替換為您實(shí)際的zip文件路徑和目標(biāo)目錄路徑,以及path/to/your/script.sh替換為您的腳本的路徑。您可以根據(jù)需要進(jìn)行進(jìn)一步的定制和修改。

0