调用7z工具更新压缩包里的文件

当我们想要更新压缩包(zip, ear应该还包括很多)里的文件(包括文件夹)时,可以通过调用7z这个工具去完成。

注意:不能更新压缩包里某个文件夹下的文件。需要用到别的方法,比如:先把这个文件夹从压缩包提取出来,再对提取出来的文件夹下的文件做修改,最后再使用这个更新的方法替换里面旧的

import部分:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

代码:

    public static void updateZipFileByCall7z() {
        String filePathStr = "E:\\Test_JAVAProgram\\test7z\\testUpdateZipFile"; // 更新的文件夹
        String updateFilePath = "E:\\Test_JAVAProgram\\test7z\\testFile.txt"; // 更新的文件
        String zipToolPath = "D:\\7-Zip\\7z.exe"; // 7z工具路径
        String sourceFilePath = "E:\\Test_JAVAProgram\\test7z\\testUpdateZipFile.zip"; // 被更新的压缩包
//        String cmd = zipToolPath + " " + "u" + " " + sourceFilePath + " " + filePathStr;
        String cmd = zipToolPath + " " + "u" + " " + sourceFilePath + " " + updateFilePath;
        System.out.println(cmd);
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            is = process.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line = null;
            while((line = br.readLine()) != null) {
                System.out.println(line);
                System.out.println(line.toLowerCase().indexOf("Everything is Ok".toLowerCase()));
                if(line.toLowerCase().indexOf("Everything is Ok".toLowerCase()) != -1) {
                    System.out.println("成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_42488909/article/details/113857168