码迷,mamicode.com
首页 > 编程语言 > 详细

java执行shell/cmd命令

时间:2017-04-26 21:36:01      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:get   stack   logs   char   process   空格   runtime类   外部程序   home   

try {
            Process p =Runtime.getRuntime().exec("chmod 777 /home/bomb/MoveToy/WebRoot/a.sh " );
            p.waitFor();
            
            Process pro = Runtime.getRuntime().exec(" /home/bomb/MoveToy/WebRoot/./a.sh " + num);
            pro.waitFor();
            System.out.println("run");
            java.io.InputStream out = pro.getInputStream();
            int i;
            String a = "";
            String b = "";
            int n=0;
            ArrayList<String> tmp = new ArrayList<String>() ;
            while ((i = out.read()) != -1) {
                char c=(char)i;
                if(i==10)
                {
                    //System.out.println(a);
                    tmp.add(a);
                    a="";
                    continue;
                }
                if(i!=13&&i!=10)
                { //System.out.println(n++ +" : "+c+" "+i);
                    a += c;
                }
            }
            
            int len=tmp.size();
            //提取耗散值
            String [] tmphaosan=new String [len];
            for(i=0;i<len;i++)
            {
                tmphaosan[i]=tmp.get(i).split(" ")[1];
                //System.out.println(tmp.get(i).split(" ")[1].split("\\n")[0]);
            }
            String ans="";
            String anss="";
            for(i=1;i<len;i++)
            {
                ans="";
                String t1=tmp.get(i-1).split(" ")[0];
                String t2=tmp.get(i).split(" ")[0];
                for(int j=0;j<t1.length();j++)
                {
                    //确保空格在后
                    if(t2.charAt(j)==‘E‘)
                    {
                        //System.out.println(j+1+" "+t1.charAt(j)+" "+t2.charAt(j));
                        ans=(j+1)+","+ans;
                    }
                    if(t1.charAt(j)==‘E‘)
                    {
                        ans+=(j+1);
                        ans+=",";
                    }
                }
                ans+=tmphaosan[i];
                ans+=‘;‘;
                anss+=ans;
            }
            //System.out.println(anss);
            PrintWriter pw = response.getWriter();
            pw.write(anss);
        } catch (Exception e) {
            System.out.println(num);
            e.printStackTrace();
        }

通过runtime类生成一个子进程,等待子线程执行完成。并且通过截获标准输出流来读取外部程序的输出内容。

java执行shell/cmd命令

标签:get   stack   logs   char   process   空格   runtime类   外部程序   home   

原文地址:http://www.cnblogs.com/superxuezhazha/p/6770657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!