我想从我正在使用终端命令的Java程序中启动/停止服务。问题是我需要以使用ProcessBuilder API的管理员身份启动终端。
public void startService(String serviceName) throws IOException, InterruptedException {
String[] cmdArray = {"cmd.exe", "/c",
"runas /savecred /profile /user:admin \"sc start " + serviceName + "\""};
Process process = new ProcessBuilder(cmdArray).start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
OutputStreamWriter output = new OutputStreamWriter(process.getOutputStream());
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line); //Prints "enter the password for admin"
}
output.write("password"); //my password
output.newLine();
output.flush();
//output.wait();
process.destroy();
}
该命令执行正常,并打印Enter the password for admin
,但是当我通过进程的输出流提供该命令时,我得到了I / O错误java.io.IOException: The pipe is being closed
。我还尝试在命令前添加echo mypassword |
,该命令不提示在终端输入密码,而是从Java程序提示。非常感谢您对此提供任何帮助。
编辑-我在output.flush()
上遇到错误