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

Mik*_*ike 12 java windows

可能重复:
从进程获取输出
从Java执行DOS命令

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

ver
Run Code Online (Sandbox Code Playgroud)

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

string result = "Windows NT 5.1"
Run Code Online (Sandbox Code Playgroud)

Kam*_*Ali 31

您可以使用以下代码

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"); 
        } 
    }
Run Code Online (Sandbox Code Playgroud)


Ran*_*Rag 5

您可以在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("]",""));
Run Code Online (Sandbox Code Playgroud)

输出= Microsoft Windows Version 6.1.7600