Java 命令行输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27577994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Command Line Output
提问by lsnow2017
I am using the following code to execute a command in java and getting the output:
我正在使用以下代码在 java 中执行命令并获取输出:
String line;
try {
System.out.println(command);
Process p = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
print(line);
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
However, apparently the command 'tree' and 'assoc' and others aren't actually their own programs that can be run through Java, rather they are coded in as parts of command prompt, so I cannot get the output. Is there actually any way to do this? Thank you
但是,显然命令“tree”和“assoc”和其他命令实际上并不是他们自己的可以通过 Java 运行的程序,而是将它们编码为命令提示符的一部分,因此我无法获得输出。实际上有没有办法做到这一点?谢谢
采纳答案by Charlie Martin
I don't have a windows machine to test this on, but generally to get the output for those builtins you run cmd.exe
as the program and pass it the command as an argument.
我没有 Windows 机器来测试它,但通常是为了获取cmd.exe
作为程序运行的那些内置函数的输出,并将命令作为参数传递给它。
Now, this has some limitations, because when the command finishes the executable stops. So if you do a cd
command, it will work, but it only affect the subprocess, not your process. For those sorts of things, if you want them to change the state of your process, you'll need to use other facilities.
现在,这有一些限制,因为当命令完成时,可执行文件会停止。因此,如果您执行cd
命令,它会起作用,但它只会影响子进程,而不是您的进程。对于这些类型的事情,如果您希望它们改变您的流程状态,您将需要使用其他工具。
This version works on a Mac:
此版本适用于 Mac:
import java.io.*;
public class cmd {
public static void
main(String[] argv){
String line;
String[] cmd = {"bash","-c","ls"};
System.out.println("Hello, world!\n");
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (Exception e) {
}
return ;
}
}