java如何实现向linux控制台输入命令啊

czs1982 2004-03-30 03:45:45
java如何实现向linux控制台输入命令啊
...全文
337 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
baixing 2004-04-04
  • 打赏
  • 举报
回复
是的,有些命令如cd 命令还是应该写入到一个shell文件里才能正常执行。

但假如你要运行echo <password> | <another command> 这种命令时,连shell这种方式也不能起作用,你可以试验一下,应该是机器停在那里没动静了。这就要麻烦些。可以这么写:
....
Runtime rt = Runtime.getRuntime();
password = passwordField.getText();
try {
Process passwordpr = rt.exec("echo" + password); //在这里passwordpr和
in = passwordpr.getInputStream(); //secondpr 各自对应了管道
//符左右的命令
Process secondpr = rt.exec("<another command>");
OutputStream out = secondpr.getOutputStream();

int a;
while((a = in.read()) != -1) {
out.write(a);
}
passwordpr.waitFor();
in.close();
out.close();

in = secondpr.getInputStream();
String consoleOut = null;
BufferedReader msgBr = new BufferedReader(new InputStreamReader(in));

while((consoleOut = msgBr.readLine()) != null) {
System.out.println("Message is: " + consoleOut);
}
secondpr.waitFor();
in.close();
msgBr.close();
} catch (Exception e1) ....

大概是这样,你可以试试。

evanxie 2004-04-02
  • 打赏
  • 举报
回复
如果你的linux命令比较复杂的话,建议把命令都写到一个shell里去,然后用java调用,例如:
Process prog=null;
prog=Runtime.getRuntime().exec("放所执行的shell文件及参数");
BufferedReader stderr = new BufferedReader(new InputStreamReader(prog.getErrorStream()));
String LineErr = stderr.readLine();
while (LineErr !=null)
{
System.out.println("LineErrError>>>"+LineErr);
LineErr = stderr.readLine();
}
int progEndWait = prog.waitFor();
stderr.close();
如果只是简单的linux 命令的话,Runtime.getRuntime().exec("ls -l")啥的应该就可以直接用了
czs1982 2004-04-02
  • 打赏
  • 举报
回复
难岛没人会吗
先实现最简单的如dir命令都行啊
czs1982 2004-04-01
  • 打赏
  • 举报
回复
那该怎么办啊
大侠指点啊
块啊毕设要啊救命啊
baixing 2004-03-31
  • 打赏
  • 举报
回复

---“在linux下Runtime.getRuntime().exec()可以吗”


是的。至少我在linux上这么干可以。
但是如果你执行的命令需要从控制台读取数据的话,就不能光靠这个方法了。还要加点别的。
那一键的风情 2004-03-31
  • 打赏
  • 举报
回复
应该先实现SSH或TELNET的客户端功能吧
czs1982 2004-03-31
  • 打赏
  • 举报
回复
就像是 windows下的 Runtime.getRuntime().exec
在linux下Runtime.getRuntime().exec()可以吗
czs1982 2004-03-31
  • 打赏
  • 举报
回复
能说清楚一点吗
czs1982 2004-03-31
  • 打赏
  • 举报
回复
怎么没人回啊
顶啊

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧