如何在 JAVA 中运行 Windows 命令并将结果文本作为字符串返回

新手上路,请多包涵

可能重复:

从进程中获取输出

从 Java 执行 DOS 命令

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

 ver

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

 string result = "Windows NT 5.1"

原文由 Mike 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 443
2 个回答

您可以为此使用以下代码

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");
        }
    }

原文由 Kamran Ali 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

根据 Senthil 在这里的回答

 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

原文由 RanRag 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题