java 实现运行dos命令

来源:互联网 发布:python while sleep 编辑:程序博客网 时间:2024/05/17 01:41

public class Test2 {

   public static void main(String[] args) throws IOException {

 String[] cmd new String[3];

         cmd[0] "cmd.exe";

         cmd[1] "/c";

         cmd[2] "arp -a";

 Runtime rt Runtime.getRuntime();    

  Process proc rt.exec(cmd);

  InputStream isInputStreamReader= proc.getInputStream();

  BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(isInputStreamReader));

 

  String length=null;

    int  i=0;

  while((length=bufferedReader.readLine())!=null)

  {

  System.out.println(length);

  i++;

  }

 

 

}

 

}

java <wbr>实现运行dos命令 

 Process

exec(String command) 
          在单独的进程中执行指定的字符串命令。

 Process

exec(String[] cmdarray) 
          在单独的进程中执行指定命令和变量。

 Process

exec(String[] cmdarray, String[] envp) 
          在指定环境的独立进程中执行指定命令和变量。

 Process

exec(String[] cmdarray, String[] envp, File dir) 
          在指定环境和工作目录的独立进程中执行指定的命令和变量。

 Process

exec(String command, String[] envp) 
          在指定环境的单独进程中执行指定的字符串命令。

 Process

exec(String command, String[] envp, File dir) 
          在有指定环境和工作目录的独立进程中执行指定的字符串命令。

abstract  InputStream

getErrorStream() 
          获取子进程的错误流。

abstract  InputStream

getInputStream() 
          获取子进程的输入流。

abstract  OutputStream

getOutputStream() 
          获取子进程的输出流。

 

 

本实例简单用java实现了win7下的cmd.exe中的命令的输出。

public class Test2 {

   public static void main(String[] args) throws IOException {

 String[] cmd new String[3];

         cmd[0] "cmd.exe";

         cmd[1] "/c";

         while(true)

{

     

         System.out.println("输入你要运行的dos命令");

         

         //对于简单的一个命令可以使用Scanner来接收用户的输入但是对于有参数的命令就不能使用它。而是使用流来操作

         

        // Scanner  scanner=new Scanner(System.in);

          

         //使用流来操作避免用户输入用参数的命令

          

         InputStreamReader   IS=new InputStreamReader(System.in);

         BufferedReader     BR=new BufferedReader(IS);

          cmd[2]=BR.readLine();

          

          

       Runtime rt Runtime.getRuntime();

   Process proc rt.exec(cmd);

   InputStream isInputStreamReader= proc.getInputStream();

   new Thread1(isInputStreamReader).start();

  

   //线程让出资源

   try {

Thread.currentThread().sleep(1000);

catch (InterruptedException e) {

 

e.printStackTrace();

}

 

}

   }

 

}

class   Thread1  extends Thread

{

private InputStream   is;

    

public Thread1(InputStream  is) {

 

this.is=is;

}

   public  void  run()

   {

   InputStreamReader  isr=new InputStreamReader(is);

   BufferedReader  br=new BufferedReader(isr);

       String  Length=null;

       try {

    while((Length=br.readLine())!=null)

    {

   System.out.println(Length);

  

    }

 

catch (IOException e) {

 

e.printStackTrace();

  

   }

}

用户可以输入dos命令带参数的命令

0 0
原创粉丝点击