The NoteBook of EricKong

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            611 Posts :: 1 Stories :: 190 Comments :: 0 Trackbacks

          1.Windows 很簡單,寫出來時為了和linux對比

             public void execWindowsCmd(String cmd) throws Exception {
                Runtime rt = Runtime.getRuntime();
                Process ppp = rt.exec(cmd);
                //input
                InputStreamReader ir = new InputStreamReader(ppp.getInputStream());
                LineNumberReader input = new LineNumberReader(ir);

                String line;
                while ((line = input.readLine()) != null)
                   com.pub.Log.logger.debug(this.getClass().getClass() + " " +
                                                     line);

                //error
                ir = new InputStreamReader(ppp.getErrorStream());
                input = new LineNumberReader(ir);
                while ((line = input.readLine()) != null)
                   com.pub.Log.logger.debug(this.getClass().getClass() + " " +
                                                     line);

                ppp.waitFor();
             }

           

          2. Linux :首先要確保對于命令,允許Web服務器的用戶是否有權限,普通命令和windows沒什么區別。Linux管道命令不能這樣直接執行,下面是具體實現fang

             public void execLinuxCmd(String cmd) throws Exception {
                Runtime rt = Runtime.getRuntime();
                File f = new File(this.fileName + PDU_SHELL);
                BufferedWriter bw = new BufferedWriter(new FileWriter(f));
                bw.write("#!/bin/bash");
                bw.newLine();
                bw.write(cmd);  //把命令寫入一個文本shell文件
                bw.flush();
                bw.close();
                cmd = f.getAbsolutePath();

                Process ppp = rt.exec("chmod a+x " + cmd);  //授權該shell文件可以執行
                ppp.waitFor();

                ppp = rt.exec(cmd);  //執行shell

                //input
                InputStreamReader ir = new InputStreamReader(ppp.getInputStream());
                LineNumberReader input = new LineNumberReader(ir);

                String line;
                while ((line = input.readLine()) != null)
                   com.pub.Log.logger.debug(this.getClass().getClass() + " " +
                                                     line);

                //error
                ir = new InputStreamReader(ppp.getErrorStream());
                input = new LineNumberReader(ir);
                while ((line = input.readLine()) != null)
                   com.pub.Log.logger.debug(this.getClass().getClass() + " " +
                                                     line);

                ppp.waitFor();

             }

          posted on 2014-12-24 12:01 Eric_jiang 閱讀(258) 評論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 伊通| 建昌县| 西安市| 蒙自县| 西青区| 富阳市| 内乡县| 博兴县| 德化县| 哈密市| 新乐市| 黔江区| 阿瓦提县| 金塔县| 历史| 和平区| 夏河县| 藁城市| 高雄市| 江津市| 大余县| 苏尼特右旗| 二连浩特市| 门头沟区| 贞丰县| 黄石市| 黑龙江省| 大同县| 旅游| 虹口区| 砚山县| 梅州市| 南开区| 耒阳市| 岑巩县| 石棉县| 安国市| 黎城县| 额济纳旗| 上蔡县| 白朗县|