【问题标题】:How to run Windows commands in JAVA and return the result text as a string [duplicate]如何在 JAVA 中运行 Windows 命令并将结果文本作为字符串返回[重复]
【发布时间】:2017-04-20 18:52:28
【问题描述】:

可能重复:
Get output from a process
Executing DOS commands from Java

我正在尝试从 JAVA 控制台程序中运行 cmd 命令,例如:

ver

然后将命令的输出返回到 JAVA 中的字符串中,例如输出:

string result = "Windows NT 5.1"

【问题讨论】:

标签: java windows


【解决方案1】:

您可以为此使用以下代码

import java.io.*; 

    public class doscmd 
    { 
        public static void main(String args[]) 
        { 
            try 
            { 
                Process p=Runtime.getRuntime().exec("cmd /c dir"); 
                p.waitFor(); 
                BufferedReader reader=new BufferedReader(
                    new InputStreamReader(p.getInputStream())
                ); 
                String line; 
                while((line = reader.readLine()) != null) 
                { 
                    System.out.println(line);
                } 

            }
            catch(IOException e1) {e1.printStackTrace();} 
            catch(InterruptedException e2) {e2.printStackTrace();} 

            System.out.println("Done"); 
        } 
    }

【讨论】:

    【解决方案2】:

    你可以在java中使用Runtime exec从java代码中执行dos命令。

    Process p = Runtime.getRuntime().exec("cmd /C ver");
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()),8*1024);
    
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    
    // read the output from the command
    
    String s = null;
    System.out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null) 
    System.out.println(s.replace("[","").replace("]",""));
    

    输出 = Microsoft Windows Version 6.1.7600

    【讨论】:

    • +1 用于 Windows 特定的解决方案...
    【解决方案3】:

    你可以这样做:

    String line;
    Process p = Runtime.getRuntime().exec ("ver");
    BufferedReader input =new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader error =new BufferedReader(new InputStreamReader(p.getErrorStream()));
    
    System.out.println("OUTPUT");
    while ((line = input.readLine()) != null)
      System.out.println(line);
    input.close();
    
    System.out.println("ERROR");
    while ((line = error.readLine()) != null)
      System.out.println(line);
    error.close();
    

    在@RanRag 的评论中,主要问题是 Windows 与 Unix/Mac。

    • WINDOWS: exec("cmd /c ver");
    • UNIX 风格:exec("ver");

    【讨论】:

    • 你需要用Process p = Runtime.getRuntime().exec("cmd /C ver");调用exec。
    【解决方案4】:

    看看java.lang.Runtime,或者更好的是java.lang.Process

    This 可能会帮助您入门。

    【讨论】:

      猜你喜欢
      • 2013-12-14
      • 1970-01-01
      • 2014-02-25
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      相关资源
      最近更新 更多