【问题标题】:how to execute dos command with options in java如何在java中执行带有选项的dos命令
【发布时间】:2010-07-30 11:39:12
【问题描述】:

我想通过java程序执行基于dos的外部命令,如果有什么办法请帮助我

【问题讨论】:

  • Java 在 DOS 上运行?

标签: java command-line


【解决方案1】:
    String[] options = new String[]{"option1", "option2"};
    Runtime.getRuntime().exec("command", options);

【讨论】:

    【解决方案2】:

    以下代码将运行 dir 命令,然后为您打印出错误信息。取自 (http://www.devdaily.com/java/edu/pj/pj010016)

    import java.io.*;
    
    public class JavaRunCommand {
    
        public static void main(String args[]) {
    
            String s = null;
    
            try {
    
            // run the Windows command (dir)
                // using the Runtime exec method:
                Process p = Runtime.getRuntime().exec("dir");
    
                BufferedReader stdInput = new BufferedReader(new 
                     InputStreamReader(p.getInputStream()));
    
                BufferedReader stdError = new BufferedReader(new 
                     InputStreamReader(p.getErrorStream()));
    
                // read the output from the command
                System.out.println("Here is the standard output of the command:\n");
                while ((s = stdInput.readLine()) != null) {
                    System.out.println(s);
                }
    
                // read any errors from the attempted command
                System.out.println("Here is the standard error of the command (if any):\n");
                while ((s = stdError.readLine()) != null) {
                    System.out.println(s);
                }
    
                System.exit(0);
            }
            catch (IOException e) {
                System.out.println("exception happened
    - here's what I know: ");
                e.printStackTrace();
                System.exit(-1);
            }
        } }
    

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 2011-08-02
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多