如何在JAVA中运行Windows命令并将结果文本作为字符串返回 [英] How to run Windows commands in JAVA and return the result text as a string
本文介绍了如何在JAVA中运行Windows命令并将结果文本作为字符串返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
从流程获取输出
执行来自Java的DOS命令
我正在尝试从内部运行cmd命令JAVA控制台程序例如:
I am trying to run a cmd command from within a JAVA console program e.g.:
ver
然后将命令的输出返回到JAVA中的字符串,例如输出:
and then return the output of the command into a string in JAVA e.g. output:
string result = "Windows NT 5.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");
}
}
这篇关于如何在JAVA中运行Windows命令并将结果文本作为字符串返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文