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 閱讀(254) 評論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 乾安县| 集贤县| 同江市| 姚安县| 禄丰县| 婺源县| 图们市| 南开区| 绥江县| 义乌市| 新宾| 潢川县| 城固县| 郎溪县| 蓬溪县| 木里| 尼勒克县| 仙游县| 抚松县| 郴州市| 宣恩县| 苍梧县| 广州市| 泗水县| 嘉义县| 徐汇区| 塔河县| 灵石县| 临夏市| 洛隆县| 和平县| 普安县| 太和县| 高淳县| 丽江市| 房产| 儋州市| 新竹县| 泗洪县| 独山县| 彰武县|