我正在尝试使用 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/