gpt4 book ai didi

java - 如何将字符串发送到终端而不是标准命令?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:22:33 24 4
gpt4 key购买 nike

我正在用 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 发送标准命令。我希望有人知道如何将普通字符串发送到终端

提前致谢

最佳答案

您的直接问题是您正在为您调用的每个“命令”启动单独的进程。密码“command”被发送给完全不知道先前“login”命令的进程。

话虽如此,您更严重的问题是严重误解了 Process 类的用途以及如何从 Java 内部与外部程序交互。

这是一个tutorial这可能有助于您进一步了解该主题,我建议其他人使用谷歌搜索。

关于java - 如何将字符串发送到终端而不是标准命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10315880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com