java - 如何知道使用 Runtime.exec() 执行的命令是给出一些输出还是只是等待而不给出任何输出?

标签 java

我正在尝试使用 Java Runtime exec 运行 Accurev 命令(如下面的代码所述)。由于我遇到网络问题,因此当执行登录命令时,该命令会继续等待响应并且不会超时。那么我应该如何处理这个错误。

private static void accurevLogin() throws IOException {
    Runtime runTime = Runtime.getRuntime();
    String userName = prop.getProperty("UserName");
    String password = prop.getProperty("Password");
    String command = (new StringBuilder("accurev login ")).append(userName).append(" ").append(password).toString();
    Process ps = null;
    try {
        ps = runTime.exec(command);
    } catch (IOException e) {
        System.out.println("Command Execution Error!");
    }
    /* Error handling Code */
    System.out.println("ACCUREV LOGGED IN");
}

当我使用时

BufferedReader input = new BufferedReader(new InputStreamReader(ps.getInputStream()));

循环中的input.readline将继续运行,我无法检查输出。

最佳答案

最好的方法是使用 Accurev 命令的超时选项(如果可用)。

如果没有这样的选项,您应该在单独的 Java 线程中执行它,并在您选择的超时后以编程方式中止。

这是一个带有简单 sleep 命令的示例:

Thread thread = new Thread() {
    public void run() {
        try {
            Process proc = Runtime.getRuntime().exec("sleep 5");
        } catch (IOException e) {
        e.printStackTrace();
        }
    }
};
thread.start();  //start thread in background
synchronized (thread) {
    try {
        thread.wait(1000L);  //your timeout
        if (thread.isAlive()) {
            System.out.println("interrupting");
            thread.interrupt();  //interrupt the thread
        }
    } catch (Exception e) {
        System.out.println("interrupted");
    }
}

关于java - 如何知道使用 Runtime.exec() 执行的命令是给出一些输出还是只是等待而不给出任何输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32647827/

相关文章:

java - 使用可执行 Jar 时将 phantomjs 作为本地资源启动

java - 在 Spark Web UI 中看不到完成的作业

java - Android API 中的上下文参数和标识符

java - 运行 Hadoop : insufficient memory for the Java Runtime Environment to continue

java - 如何通过 hibernate 访问 pl/sql 过程中的输出参数

java - 在 android 模拟器上按下按钮时发出通知

java - Avro 架构 : List of generic types

java - EAR 中的依赖关系管理

java - (java) 使用 HtmlUnit 监听 websocket 消息

java - .wav 文件可以播放,但 .aiff 文件不能播放