我想从java运行Windows命令行命令并将结果返回到java。这可能吗?
例如,我想做以下
Object returnValue = runOnCommandLine(“wmic cpu get LoadPercentage”); //在这种情况下,returnValue是作为String
的cpu加载百分比编辑:我能够正常工作
InputStream inputStream = new ProcessBuilder("wmic", "cpu", "get", "status").start().getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer);
String theString = writer.toString();
System.out.println("My string: " + theString);
答案 0 :(得分:1)
您需要的数据是commandOutput。
String cmd = "wmic cpu get LoadPercentage";
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader stdin = new BufferedReader(
new InputStreamReader(p.getInputStream()));
StringBuilder commandOutput = new StringBuilder();
String line;
while ((line = stdin.readLine()) != null) {
commandOutput.append(line);
}
int exitValue = -1;
try {
exitValue = p.waitFor();
} catch (InterruptedException e) {
// do something here
}
答案 1 :(得分:0)
看看ProcessBuilder。
在Java 1.5之下使用了Runtime.getRuntime().exec(...)
。
答案 2 :(得分:0)
您可以执行以下操作:
Process proc = Runtime.getRuntime().exec("net start");
InputStreamReader isr = new InputStreamReader(proc.getInputStream());
BufferedReader br = new BufferedReader(isr);
String temp = null;
while (( temp = br.readLine() ) != null)
System.out.println(temp);