我有一个命令,我从我的Java程序执行,如: -
String command="C:\\my\\abc.bat";
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
process.waitFor();
现在这个命令从命令行运行时要求输入密码。它会在这里吗?我怎么能写出密码呢。
实施例: - 1)运行命令。 2)输入密码: -
我完成了第一步。如何在执行密码后输入密码。
答案 0 :(得分:1)
使用此语法将密码作为CLI参数传递:
String password = "your password"
Runtime.getRuntime().exec(new String[]{"C:\\my\\abc.bat", password});
或者,如果您的程序是交互式的,请使用getOutputStream()
来获取写入密码的输出流。例如:
String password = "your password"
PrintWriter writer = new PrintWriter(process.getOutputStream());
writer.println(password);
writer.close();
请注意,这是一个简化示例,您必须适当地管理异常。
答案 1 :(得分:0)
使用: -
解决它String command="C:\\my\\abc.bat";
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
OutputStream out=process.getOutputStream();
out.write("mypass".getBytes());
out.flush();
同时删除 waitFor()
,导致流关闭。