大夢想家

          5年開發工程師,2年實施經理,X年售前顧問,......
          數據加載中……
          如何用java啟動windows命令行程序

          先請編譯和運行下面程序:
          import java.util.*;
          import java.io.*;
          public class BadExecJavac2
          {
              public static void main(String args[])
              {
                  try
                  {            
                      Runtime rt = Runtime.getRuntime();
                      Process proc = rt.exec("javac");
                      int exitVal = proc.waitFor();
                      System.out.println("Process exitValue: " + exitVal);
                  } catch (Throwable t){
                      t.printStackTrace();
                  }
              }
          }

             我們知道javac命令,當不帶參數運行javac 程序時,它將輸出幫助說明,為什么上面程序不產生任何輸出并掛起,永不完成呢?java文檔上說,由于有些本地平臺為標準輸入和輸出流所提供的緩沖區大小有限,如果不能及時寫入子進程的輸入流或者讀取子進程的輸出流,可能導致子進程阻塞,甚至陷入死鎖。所以,上面的程序應改寫為:
          import java.util.*;
          import java.io.*;
          public class MediocreExecJavac
          {
              public static void main(String args[])
              {
                  try
                  {            
                      Runtime rt = Runtime.getRuntime();
                      Process proc = rt.exec("javac");
                      InputStream stderr = proc.getErrorStream();
                      InputStreamReader isr = new InputStreamReader(stderr);
                      BufferedReader br = new BufferedReader(isr);
                      String line = null;
                      System.out.println("<ERROR>");
                      while ( (line = br.readLine()) != null)
                          System.out.println(line);
                      System.out.println("</ERROR>");
                      int exitVal = proc.waitFor();
                      System.out.println("Process exitValue: " + exitVal);
                  } catch (Throwable t){
                      t.printStackTrace();
                  }
              }
          }
          下面是正確的輸出:
          D:\java>java   MediocreExecJavac
          <ERROR>
          Usage: javac <options> <source files>
          where possible options include:
            -g                         Generate all debugging info
            -g:none                    Generate no debugging info
            -g:{lines,vars,source}     Generate only some debugging info
            -nowarn                    Generate no warnings
            -verbose                   Output messages about what the compiler is doing
            -deprecation               Output source locations where deprecated APIs are used
            -classpath <path>          Specify where to find user class files
            -cp <path>                 Specify where to find user class files
            -sourcepath <path>         Specify where to find input source files
            -bootclasspath <path>      Override location of bootstrap class files
            -extdirs <dirs>            Override location of installed extensions
            -endorseddirs <dirs>       Override location of endorsed standards path
            -d <directory>             Specify where to place generated class files
            -encoding <encoding>       Specify character encoding used by source files
            -source <release>          Provide source compatibility with specified release
            -target <release>          Generate class files for specific VM version
            -version                   Version information
            -help                      Print a synopsis of standard options
            -X                         Print a synopsis of nonstandard options
            -J<flag>                   Pass <flag> directly to the runtime system
          </ERROR>
          Process exitValue: 2
          D:\java>
             下面是一個更一般的程序,它用兩個線程同步清空標準錯誤流和標準輸出流,并能根據你所使用的windows操作系統選擇windows命令解釋器command.com或cmd.exe,然后執行你提供的命令。
          import java.util.*;
          import java.io.*;
          class StreamGobbler extends Thread
          {
              InputStream is;
              String type;  //輸出流的類型ERROR或OUTPUT
              StreamGobbler(InputStream is, String type)
              {
                  this.is = is;
                  this.type = type;
              }
              public void run()
              {
                  try
                  {
                      InputStreamReader isr = new InputStreamReader(is);
                      BufferedReader br = new BufferedReader(isr);
                      String line=null;
                      while ( (line = br.readLine()) != null)
                      {
                          System.out.println(type + ">" + line);
                          System.out.flush();
                      }
                      } catch (IOException ioe)
                        {
                          ioe.printStackTrace();  
                        }
              }
          }
          public class GoodWindowsExec
          {
              public static void main(String args[])
              {
                  if (args.length < 1)
                  {
                      System.out.println("USAGE: java GoodWindowsExec <cmd>");
                      System.exit(1);
                  }
                  try
                  {            
                      String osName = System.getProperty("os.name" );
                      System.out.println("osName: " + osName);
                      String[] cmd = new String[3];
                      if(osName.equals("Windows XP") ||osName.equals("Windows 2000"))
                      {
                          cmd[0] = "cmd.exe" ;
                          cmd[1] = "/C" ;
                          cmd[2] = args[0];
                      }
                      else if( osName.equals( "Windows 98" ) )
                      {
                          cmd[0] = "command.com" ;
                          cmd[1] = "/C" ;
                          cmd[2] = args[0];
                      }
                      Runtime rt = Runtime.getRuntime();
                      System.out.println("Execing " + cmd[0] + " " + cmd[1]+ " " + cmd[2]);
                      Process proc = rt.exec(cmd);
                      // any error message?
                      StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");       
                      // any output?
                      StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
                      // kick them off
                      errorGobbler.start();
                      outputGobbler.start();
                      // any error???
                      int exitVal = proc.waitFor();
                      System.out.println("ExitValue: " + exitVal);
                  } catch (Throwable t){
                      t.printStackTrace();
                  }
              }
          }
          下面是一個測試結果:
          D:\java>java  GoodWindowsExec "copy Test.java Test1.java"
          osName: Windows XP
          Execing cmd.exe /C copy Test.java Test1.java
          OUTPUT>已復制         1 個文件。
          ExitValue: 0
          D:\java>
          下面的測試都能通過(windows xp+jdk1.5)
          D:\java>java   GoodWindowsExec dir
          D:\java>java   GoodWindowsExec Test.java
          D:\java>java   GoodWindowsExec regedit.exe
          D:\java>java   GoodWindowsExec NOTEPAD.EXE
          D:\java>java   GoodWindowsExec first.ppt
          D:\java>java   GoodWindowsExec second.doc



          客戶虐我千百遍,我待客戶如初戀!

          posted on 2007-12-26 13:10 阿南 閱讀(739) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 城市| 洛浦县| 噶尔县| 潮州市| 丁青县| 祥云县| 即墨市| 连南| 来宾市| 洪江市| 师宗县| 周至县| 玉田县| 达州市| 南宫市| 湘潭县| 鲁甸县| 铜山县| 上虞市| 威海市| 红原县| 封开县| 轮台县| 奈曼旗| 厦门市| 灵丘县| 淳化县| 湘潭县| 昌图县| 天气| 美姑县| 徐州市| 阿克| 东阿县| 都兰县| 瑞安市| 南雄市| 容城县| 惠东县| 固原市| 万全县|