我正在用Java编写一个程序,需要使用终端命令才能工作。
我的功能基本上是这样的:
public void sendLoginCommand() throws IOException
{
System.out.println("\n------------Sending Login Command------------\n");
String cmd="qskdjqhsdqsd";
Runtime rt = Runtime.getRuntime();
Process p=rt.exec(cmd);
}
public Process sendPassword(String password) throws IOException
{
System.out.println("\n------------Sending Password------------\n");
String cmd=password;
Runtime rt = Runtime.getRuntime();
Process p=rt.exec(cmd);
return p;
}
public void login(String password) throws IOException
{
sendLoginCommand();
Process p = sendPassword(password);
System.out.println("\n------------Reading Terminal Output------------\n");
Reader in = new InputStreamReader(p.getInputStream());
in = new BufferedReader(in);
char[] buffer = new char[20];
int len = in.read(buffer);
String s = new String(buffer, 0, len);
System.out.println(s);
if(s.equals("Password invalid.")) loggedIn=false;
else loggedIn=true;
}
在这里,程序正确发送了 p4 登录命令,但随后终端要求输入密码。
当我使用与 sendLoginCommand() 相同的行时,程序返回错误。
显然,我们只能通过 Process 发送标准命令。
我希望有人知道如何将普通字符串发送到终端
先感谢您
您面临的直接问题是您正在为您调用的每个“命令”启动单独的进程。密码“命令”被发送到一个完全不知道先前的“登录”命令的进程。
话虽如此,您更可怕的问题是对 Process 类的用途以及如何从 Java 内部与外部程序进行交互的严重误解。
这是一个tutorial这可能有助于您进一步了解该主题,我建议其他人使用谷歌搜索。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)