import java.io.*;
class PT
{
  public static void main(String[] args) throws IOException
  {
  String filename="out.txt";
  if(args.length>0){
  filename=args[0];
  }
  String command="cmd /C dir";
  Runtime r=Runtime.getRuntime();
  Process p=r.exec(command);
  BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
  PrintStream ps=new PrintStream(new FileOutputStream(filename));
  String inline;
  while(null!=(inline=br.readLine())){
  ps.println(inline);
  }
  System.out.println("a command result has been readed to a file "+filename);
  }
}

解决方案 »

  1.   

    谢谢楼上的,那么怎样才能把dir的结果直接保存在字符串变量中呢
    而不是存入文件?谢谢!
      

  2.   

    mport java.io.*;
    class PT
    {
      public static void main(String[] args) throws IOException
      {
      String filename="out.txt";
      if(args.length>0){
      filename=args[0];
      }
      String command="cmd /C dir";
      Runtime r=Runtime.getRuntime();
      Process p=r.exec(command);
      BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
      StringBuffer sb=new StringBuffer();
      String inline;
      while(null!=(inline=br.readLine())){
      sb.append(inline).append("\n");
      }
     
      System.out.println(sb.toString());
      }
    }
      

  3.   

    这样:
    import java.io.*;
    class PT
    {
      public static void main(String[] args) throws IOException
      {
     
      String command="cmd /C dir";
      Runtime r=Runtime.getRuntime();
      Process p=r.exec(command);
      BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
      StringBuffer sb=new StringBuffer();
      String inline;
      while(null!=(inline=br.readLine())){
      sb.append(inline).append("\n");
      }
     
      System.out.println(sb.toString());
      }
    }
      

  4.   

    非常谢谢!马上就给分,我在Linux下面试了,发觉要这样才能执行
    String command="ls"; 不能String command="cmd /C ls";
    不是说JAVA是一次编译,到处使用的吗?
      

  5.   

    请问JAVA如何执行(调用)操作系统命令,如dir,然后把执行结果存入变量或文件,谢谢!??
    可是你要调用操作系统命令呀,当然和操作系统有关