How to send a string to the terminal without having it to be a standard command?(如何在不作为标准命令的情况下将字符串发送到终端?)
问题描述
我正在用 Java 编写一个需要使用终端命令才能工作的程序.我的功能基本上是这样的:
I am writing a program in Java that needs to use terminal command to work. My function basically looks like this :
public void sendLoginCommand() throws IOException
{
System.out.println("
------------Sending Login Command------------
");
String cmd="qskdjqhsdqsd";
Runtime rt = Runtime.getRuntime();
Process p=rt.exec(cmd);
}
public Process sendPassword(String password) throws IOException
{
System.out.println("
------------Sending Password------------
");
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("
------------Reading Terminal Output------------
");
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 发送标准命令.我希望有人知道如何向终端发送普通字符串
Here, the program sends correctly th p4 login command, but then, the terminal asks for a password. When I use the same lines that with the sendLoginCommand(), the program returns an error. Apparently, we can send only standard commands throught Process. I was hoping that someone knew how to send a normal string to the terminal
提前谢谢你
推荐答案
我找到了我的问题的答案.
I have found the answer to my question.
问题是终端的第二个响应实际上是在第一个响应中,并且必须在其中发送密码.这是代码(我同意,我的解释有点模糊):
The problem was that the second response of the terminal was in fact in the first one, and the password had to be sent in the middle of it. Here is the code (I agree, my explanation is a little vague) :
String s="";
Process p = Runtime.getRuntime().exec("p4 login");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
char a=(char)in.read();
while(a>0 && a<256)
{
a=(char)in.read();
if(nb==14) new PrintWriter(p.getOutputStream(),true).println(password);
if(nb>16) s=s+a;
nb++;
}
if(s.startsWith("User")) loggedIn=true;
else loggedIn=false;
这篇关于如何在不作为标准命令的情况下将字符串发送到终端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不作为标准命令的情况下将字符串发送到终端?


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 转换 ldap 日期 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01