LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 4552|回复: 6

请教java 调用shell 命令的问题

[复制链接]
发表于 2005-4-6 22:35:01 | 显示全部楼层 |阅读模式
程序代码如下:
public class test{
   public static void main(String args[]){
          Runtime rt=getRuntime();
          rt.exec("bash","test.sh");
    }
}
运行没错,但没有执行bash test.sh。请教想执行起来的话该怎么修改?
发表于 2005-4-7 08:52:02 | 显示全部楼层
完整的程序如下
import java.io.*;
import java.util.ArrayList;

public class test {
        public static void main(String args[]) throws Exception
        {
                System.out.println("Hello World!");
                Runtime hello=Runtime.getRuntime();
                String cmd[]={"bash","ls.sh"};
                hello.exec(cmd);
        }
}
而且下面的语句已经执行。
System.out.println("Hello World!");结果只显示HelloWorld!
回复 支持 反对

使用道具 举报

发表于 2005-4-14 11:57:00 | 显示全部楼层
经过研究,正确的程序如下:
public class test{
public static void main(String args[]){
Runtime rt=Runtime.getRuntime();
                String str[]={"/bin/sh","-c","sh test.sh"};
                Process pcs=rt.exec(str);
                BufferedReader br = new BufferedReader(new InputStreamReader(pcs.getInputStream()));
                String line=new String();
                while((line = br.readLine()) != null)
                {
                       System.out.println(line);
                }
                try{
                pcs.waitFor();
                }
                catch(InterruptedException e){
                        System.err.println("processes was interrupted");
                }
                br.close();
                int ret=pcs.exitValue();
                System.out.println(ret);

}
}
回复 支持 反对

使用道具 举报

发表于 2005-4-15 09:53:59 | 显示全部楼层
等一下吧
回复 支持 反对

使用道具 举报

发表于 2005-4-15 09:55:06 | 显示全部楼层
打错字了,应该是顶一下吧:-)
回复 支持 反对

使用道具 举报

发表于 2010-5-14 10:16:57 | 显示全部楼层
很好。很强大。
回复 支持 反对

使用道具 举报

发表于 2010-5-14 17:16:01 | 显示全部楼层
很好。很强大。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表