如何在Java中写入和读取命令行? [英] How to write into and read from command line in Java ?
问题描述
可能重复:
Java外部程序
我试图写一个程序来写一个命令在命令行上,
I am trying to wrtie a program to write a command on a command line,
例如;
ipconfig
ipconfig
然后得到命令的响应,所以我想同时写入命令命令行并获得其响应。我在网上搜索它,看到apache cli是用来做这个Java,但实际上我没有清楚地得到如何做。你能请我帮助我关于我的情况与几行代码或教程有关写作和阅读命令吗?
and then get the response of the command so I want to both write command to a command line and get its response. I have searched about it on the net and saw that apache cli is used to do this in Java but actually I did not clearly get how it can be done. Can you please help me about my situation with a few line of codes or tutorials about both writing and reading commands please?
非常感谢你
推荐答案
您可以以 Process
开头,捕获 InputStream
,如下所述 here :
You could start it as a Process
and capture the InputStream
of the process as described here:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ipconfig"); // you might need the full path
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
编辑:我从上面的链接复制此代码,但代码似乎错误。你不需要这个输出流吗?编辑2:不。
I copied this code from above link, but the code seems wrong. Don't you need the output stream for this? no.
getInputStream()
getInputStream()
获取输入流的子进程。流从
此Process对象表示的进程的标准输出流中获取数据
。
Gets the input stream of the subprocess. The stream obtains data piped from the standard output stream of the process represented by this Process object.
很好的命名约定...
Nice naming convention...
这篇关于如何在Java中写入和读取命令行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!