将CMD命令输出到控制台!

来源:互联网 发布:c语言预处理命令三种 编辑:程序博客网 时间:2024/06/06 17:45
  1. package com.eshore.sweetop.io;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. public class OSExecute {
  5.     public static void command(String command) {
  6.         try {
  7.             Process process=new ProcessBuilder(command.split(" ")).start();
  8.             BufferedReader results=new BufferedReader(new InputStreamReader(process.getInputStream()));
  9.             String s;
  10.             while((s=results.readLine())!=null){
  11.                 System.out.println(s);
  12.             }
  13.             BufferedReader errors=new BufferedReader(new InputStreamReader(process.getErrorStream()));
  14.             while((s=errors.readLine())!=null){
  15.                 System.err.println(s);
  16.             }
  17.         } catch (Exception e) {
  18.             if(!command.startsWith("CMD /C")){
  19.                 command("CMD /C"+command);
  20.             }else{
  21.                 throw new RuntimeException(e);
  22.             }
  23.         }
  24.     }
  25.     
  26.     public static void main(String[] args) {
  27.         OSExecute.command("dir");
  28.     }
  29. }
  30. package com.eshore.sweetop.io;
  31. import java.io.BufferedReader;
  32. import java.io.InputStreamReader;
  33. public class OSExecute {
  34.     public static void command(String command) {
  35.         try {
  36.             Process process=new ProcessBuilder(command.split(" ")).start();
  37.             BufferedReader results=new BufferedReader(new InputStreamReader(process.getInputStream()));
  38.             String s;
  39.             while((s=results.readLine())!=null){
  40.                 System.out.println(s);
  41.             }
  42.             BufferedReader errors=new BufferedReader(new InputStreamReader(process.getErrorStream()));
  43.             while((s=errors.readLine())!=null){
  44.                 System.err.println(s);
  45.             }
  46.         } catch (Exception e) {
  47.             if(!command.startsWith("CMD /C")){
  48.                 command("CMD /C"+command);
  49.             }else{
  50.                 throw new RuntimeException(e);
  51.             }
  52.         }
  53.     }
  54.     
  55.     public static void main(String[] args) {
  56.         OSExecute.command("dir");
  57.     }
  58. }
原创粉丝点击