熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java執行Shell&Command

2022-06-13   來源: Java核心技術 

  主要使用Runtime和Process兩個類其中如何對Process進行輸入是關鍵尤其注意在合適的時候flush輸出流

  package shelltest;

  import javaioBufferedReader;

  import javaioIOException;

  import javaioInputStreamReader;

  import javaioOutputStreamWriter;

  import javaioPrintWriter;

  import javautilloggingLevel;

  import javautilloggingLogger;

  /**

  *

  * @author WeiLiu

  */

  public class Shell {

  private Process pro = null;

  private Runtime runTime = null;

  public Shell() {

  runTime = RuntimegetRuntime();

  if (runTime == null) {

  Systemerrprintln(Create runtime false!);

  Systemexit();

  }

  }

  public void execueteCommand(String command) throws InterruptedException {

  Systemoutprintln(************************);

  Systemoutprintln(Execute command :+command);

  Systemoutprintln(Result:);

  try {

  pro = runTimeexec(command);

  BufferedReader input = new BufferedReader(new InputStreamReader(pro                                             getInputStream()));//這個輸入流是獲取shell輸出的

  PrintWriter output= new PrintWriter(new OutputStreamWriter(progetOu                                             tputStream()));//這個輸出流主要是對Process進行輸入控制用的

  String line;

  while ((line = inputreadLine()) != null) {

  Systemoutprintln(line);

  if( != lineindexOf(your name)){//當檢測到提示輸入時則執行輸入操作

  outputprint(liuwei\r\n);// \r\n 不可少否則相當於沒有Enter操作

  outputflush();//輸入完成之後一定要flush否則一直處在等待輸入的地方

  }

  }

  Systemoutprintln(************************\n);

  inputclose();

  outputclose();

  prodestroy();

  } catch (IOException ex) {

  LoggergetLogger(ShellclassgetName())log(LevelSEVERE null ex);

  }

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/27038.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.