【发布时间】:2023-03-14 09:51:01
【问题描述】:
我正在尝试执行不在默认工作目录中的 bat 文件(来自 java 内)。我尝试了下面的代码,但它似乎不适用于“CD”命令。
String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
/////////////////////////////////////// ////////// 这是应该执行命令的代码 ///////////////////////////////////////// //////
String command = "cd C:\usmt" ;
//in windows
//String command = "ping -n 3 " + domainName;
String output = obj.executeCommand(command);
System.out.println(output);
【问题讨论】:
-
你给出了什么意见。你得到什么输出。你期待什么输出?当你调试它时会发生什么?发布新问题时,您应该始终回答这些问题。代码已经成功了一半,现在我们需要了解您在做什么。
-
使用
ProcessBuilder,它有directory属性,允许你指定执行命令时使用的工作目录 -
当 windows 执行系统命令时,它会创建一个新的 shell,就像我打开两个 cmd 提示符它们有不同的工作目录一样。
标签: java powershell cmd