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

Java調用Windows控制台命令

2013-11-23 19:23:53  來源: Java核心技術 

  方法一

  public static void main(String[] args)

  {

  InputStream ins = null;

  String[] cmd = new String[]{ cmdexe /C ipconfig };

  try

  {

  Process process = RuntimegetRuntime()exec(cmd);

  // cmd 的信息

  ins = processgetInputStream();

  BufferedReader reader = new BufferedReader(new InputStreamReader(

  ins));

  String line = null;

  while ((line = readerreadLine()) != null)

  {

  // 輸出

  Systemoutprintln(line);

  }

  int exitValue = processwaitFor();

  Systemoutprintln(返回值 + exitValue);

  // 關閉

  processgetOutputStream()close();

  }

  catch (Exception e)

  {

  eprintStackTrace();

  }

  方法二

  class StreamDrainer implements Runnable

  {

  private InputStream ins;

  public StreamDrainer(InputStream ins)

  {

  thisins = ins;

  }

  public void run()

  {

  try

  {

  BufferedReader reader = new BufferedReader(new InputStreamReader(ins));

  String line = null;

  while ((line = readerreadLine()) != null)

  {

  Systemoutprintln(line);

  }

  }

  catch (Exception e)

  {

  eprintStackTrace();

  }

  }

  }

  public class CMD

  {

  public static void main(String[] args)

  {

  // String[] cmd = new String[] { cmdexe /C

  // wmic process get name };

  String[] cmd = new String[]

  { cmdexe /C ipconfig };

  try

  {

  Process process = RuntimegetRuntime()exec(cmd);

  new Thread(new StreamDrainer(processgetInputStream()))start();

  new Thread(new StreamDrainer(processgetErrorStream()))start();

  processgetOutputStream()close();

  int exitValue = processwaitFor();

  Systemoutprintln(返回值 + exitValue);

  }

  catch (Exception e)

  {

  eprintStackTrace();

  }

  }

  }

  本篇文章來源於 :劉志猛博客 原文鏈接


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