在我的Java应用程序中,我正在使用exec()命令来调用终端函数:

p = Runtime.getRuntime().exec(command);
p.waitFor();


该呼叫使用zipunzip呼叫。我最初打电话给:

zip -P password -r encrypted.zip folderIWantToZip


当我通过java调用unzip函数时,我将密码指定为方法参数。如果指定了正确的密码,则呼叫应unzip加密的文件夹:

unzip -P password encrypted.zip


我想要一种方法来确定输入的密码是否错误。例如,如果password是正确的,则该调用将正确 zip文件。但是我注意到,对于不正确的密码,不会引发任何异常。我该如何确定?

最佳答案

您可以阅读流程的ErrorStream和InputStream以确定流程的输出。下面给出示例代码

    public static void main(String[] args) {
    try {
        String command = "zip -P password -r encrypted.zip folderIWantToZip";
        Process p = Runtime.getRuntime().exec(command);
        InputStream is = p.getInputStream();
        int waitFor = p.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));


        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println("line:" + line);
        }
        is = p.getErrorStream();
        reader = new BufferedReader(new InputStreamReader(is));
        while ((line = reader.readLine()) != null) {
            System.out.println("ErrorStream:line: " + line);
        }
        System.out.println("waitFor:" + waitFor);
        System.out.println("exitValue:" + p.exitValue());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


您也可以使用退出代码来验证过程状态,但这是特定于程序的。通常零表示成功终止,否则异常终止。

10-08 14:56