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 閱讀(253) 評論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 清远市| 盱眙县| 桃园市| 衢州市| 兴业县| 西吉县| 疏勒县| 锡林浩特市| 新密市| 陇南市| 合川市| 大田县| 西青区| 竹山县| 金阳县| 左贡县| 弥渡县| 哈巴河县| 涞水县| 广平县| 阿拉善左旗| 淮阳县| 平原县| 徐水县| 灵石县| 青冈县| 塘沽区| 美姑县| 武汉市| 巨鹿县| 定西市| 定边县| 南城县| 象山县| 柳林县| 德江县| 海兴县| 固始县| 大埔县| 甘南县| 寿光市|