[英]How to open linux terminal from java and be able to execute commands in it?
[英]How to execute multiple commands interactively in linux terminal from Java?
我想在linux terminal
运行多个命令,该命令将如下所示:
1.我会跑假设torch
和我写了th
命令,并将其打开火炬PROMT。
2.现在,如果我从Java执行下一条命令,那么它将在linux终端的割炬程序中运行。
您可以举另一个例子:
1.首先,我将从Java在linux终端中运行python
。
2.然后从Java运行python解释器中的1+1
或任何东西。
所以在这里,我的第二条命令取决于第一条命令。 我想按顺序在终端中运行命令。
编辑 :另一种方法会做。假设我有一个在linux终端中运行的python解释器,现在我想从java中执行一个命令,该命令将在特定打开的linux终端的python解释器中运行。 我可以这样做吗?
我试图使用以下命令运行命令:
String line;
try
{
String execstr= "th"; //It opens the torch promt in linux terminal.
Process p = Runtime.getRuntime().exec(execstr);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
/*if((line= input.readLine())==null)
System.out.println("blank");*/
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
但是现在在执行此命令之后,如何在promt中从java运行命令,这意味着我希望以交互方式进行操作?
那么,如何保存上一个命令的状态并将其用于下一个命令?
使用p.getOutputStream()
获取一个流,您可以在其中为运行的程序编写所需的输入。 (我知道,命名有点混乱)。
只是相关的部分:
Process p = Runtime.getRuntime().exec(execstr);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
OutputStream ops = p.getOutputStream();
ops.write("echo hello world".getBytes());
ops.close();
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
input.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.