从Java返回Windows cmd文本? [英] Return Windows cmd text from Java?

查看:50
本文介绍了从Java返回Windows cmd文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回在Windows中的cmd提示符下手动键入命令时返回的相同文本.这是一个起作用的示例.

I want to return the same text that is returned when I manually type a command into the cmd prompt in Windows. Here is an example that does not work.

import java.io.IOException;

public class Test {

    public static void main(String[] args) throws IOException {
        String g = "";
        Runtime.getRuntime().exec(new String[] {"ipconfig", g});  
        System.out.println(g);
    }
}

我不知道是否应该研究Runtime.getRuntime()exec,因为我了解api的方式(猜测,意味着什么都没有返回,但是过程开始了.我在示例中使用了ipconfig,但实际上我需要运行各种诊断命令并分析字符串(我将其称为"cmd提示").

I don't know if I should be looking into Runtime.getRuntime()exec because the way I understand the api ( http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html ) is that of all of the exec examples, none return a string. The return value (if I understand right) on some is actually a 'process' which I can only guess means nothing gets returned, but the process is started. I used ipconfig in the example, but I actually need to run various diagnostic commands and analyze the string (which I have referred to as the 'cmd prompt').

推荐答案

要捕获命令的输出,可以使用以下命令:

To capture the output of the command, you can use this:

Process p = Runtime.getRuntime().exec(new String[] {"ipconfig", g});
InputStream s = p.getInputStream();

BufferedReader in = new BufferedReader(new InputStreamReader(s));
String temp;

while ((temp = in.readLine()) != null) {
    System.out.println(temp);
}

请不要在读取输入或过程终止之前将readLine()方法阻塞.

Please not that the readLine() method will block until it reads an input or the process is terminated.

这篇关于从Java返回Windows cmd文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆