检测Java中的终端命令错误

时间:2015-01-21 23:49:31

标签: java encryption terminal passwords

在我的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正确,则调用将正确unzip zip文件。但我注意到,不正确的密码不会引发异常。我该如何确定?

2 个答案:

答案 0 :(得分:1)

您可以阅读进程的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();
    }
}

您也可以使用exitcode验证流程状态,但它特定于程序。通常为零意味着成功终止,否则异常终止。

答案 1 :(得分:1)

根据我的评论,我要做的第一件事就是通过getInputStream()和getErrorStream()来捕获Process的InputStream和ErrorStream,尤其是后者,ErrorStream,并检查输出是什么输出错误。请注意,这些必须在他们自己的线程中完成,否则你将占用你的程序。我通常会使用某种类型的StreamGobbler类。另外,不要忽略p.waitFor()返回的int。

如,

  ProcessBuilder pBuilder = new ProcessBuilder(COMMAND);
  Process process = null;
  try {
     process = pBuilder.start();

     new Thread(new StreamGobbler("Input", process.getInputStream())).start();
     new Thread(new StreamGobbler("Error", process.getErrorStream())).start();

     int exitValue = process.waitFor();
     System.out.println("Exit Value: " + exitValue);
     process.destroy();


  } catch (IOException e) {
     e.printStackTrace();
  } catch (InterruptedException e) {
     e.printStackTrace();
  } finally {
     if (process != null) {
        process.destroy();
     }
  }

class StreamGobbler implements Runnable {
   private String name;
   private Scanner scanner;

   public StreamGobbler(String name, InputStream inputStream) {
      this.name = name;
      scanner = new Scanner(inputStream);
   }

   @Override
   public void run() {
      while (scanner.hasNextLine()) {
         String line = scanner.nextLine();
         System.out.println(name + ": " + line); // or better, log the line
      }
      scanner.close();
   }
}