使用 java 在 cmd 中执行 "time" 命令
Execute "time" command in cmd using java
我需要在命令提示符下使用 java 执行 "time" 命令。它的问题是在显示时间后,它要求设置一个新时间。我可以正常执行 "dir" 或 "cd" 或 "ver" 等命令。但是那些要求用户输入的命令,如 "date" 或 "time" 无法完全执行。这是代码:
try {
Process p = Runtime.getRuntime().exec("cmd /c time");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException e1) {} catch (InterruptedException e2) {}
我怀疑是因为 cmd 正在请求输入,所以它不能被 InputStream 读取,因为它认为流还没有结束,因此程序永远不会停止执行。
所以,我正在寻找的是一种在它要求我时输入新时间然后打印输出(如果有的话)的方法。
如果您唯一关心的是第一个输出,那么您不应该等待进程退出 (p.waitFor()
),而是继续获取输入流并读取行,例如下面的代码。
try {
String [] commands = {"cmd.exe","/C","time"};
Process p = Runtime.getRuntime().exec(commands);
OutputStream out = p.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine(); // read the first line
System.out.println(line);
// write to ouput
out.write("sample".getBytes());
out.flush();
line = reader.readLine();
System.out.println(line);
line = reader.readLine();
System.out.println(line);
p.destroy();
} catch (IOException e1) {}
我需要在命令提示符下使用 java 执行 "time" 命令。它的问题是在显示时间后,它要求设置一个新时间。我可以正常执行 "dir" 或 "cd" 或 "ver" 等命令。但是那些要求用户输入的命令,如 "date" 或 "time" 无法完全执行。这是代码:
try {
Process p = Runtime.getRuntime().exec("cmd /c time");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException e1) {} catch (InterruptedException e2) {}
我怀疑是因为 cmd 正在请求输入,所以它不能被 InputStream 读取,因为它认为流还没有结束,因此程序永远不会停止执行。 所以,我正在寻找的是一种在它要求我时输入新时间然后打印输出(如果有的话)的方法。
如果您唯一关心的是第一个输出,那么您不应该等待进程退出 (p.waitFor()
),而是继续获取输入流并读取行,例如下面的代码。
try {
String [] commands = {"cmd.exe","/C","time"};
Process p = Runtime.getRuntime().exec(commands);
OutputStream out = p.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine(); // read the first line
System.out.println(line);
// write to ouput
out.write("sample".getBytes());
out.flush();
line = reader.readLine();
System.out.println(line);
line = reader.readLine();
System.out.println(line);
p.destroy();
} catch (IOException e1) {}