[英]Executing custom Commands in Java
With this, we can execute "build in" commands in java. 这样,我们就可以在Java中执行“内置”命令。 However if we want to run some custom commands from this , Changing "pwd" to "device_id -l" doesn't work.
但是,如果我们要运行一些自定义命令此 ,更改“PWD”到“DEVICE_ID -l”不起作用。 "device_id -l" should list all the ids of attached devices of currently host.
“ device_id -l”应列出当前主机连接的设备的所有ID。 if "device_id -l" is executed in terminal itself.
如果在终端本身执行“ device_id -l”。 it works fine.
它工作正常。 There is not a question for the "build in" bash commands.
bash命令“内置”没有问题。 Thank you.
谢谢。
String cmd = "pwd";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null)
System.out.println(line);
We can excuate 我们可以讨价还价
You can try using ProcessBuilder . 您可以尝试使用ProcessBuilder 。
// create process
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "device_id", "-l");
// start process
Process p = pb.start();
// wait for process exit
p.waitFor();
// read process output
BufferedReader buf = new BufferedReader(newInputStreamReader(p.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null)
System.out.println(line);
You need to split your command+arguments to a String array. 您需要将Command +参数拆分为String数组。 In your case, if you want to execute "device_id -l", split that into an array like this:
在您的情况下,如果要执行“ device_id -l”,请将其拆分为如下数组:
String[] cmd = new String[] {"/full/path/to/device_id", "-l"};
Process pr = Runtime.getRuntime().exec(cmd);
And, you might want to use ProcessBuilder . 并且,您可能想要使用ProcessBuilder 。
String[] cmd = new String[] {"/full/path/to/device_id", "-l"};
ProcessBuilder pb = new ProcessBuilder(cmd);
Process pr = pb.start();
Finally, you'll have to take into account that Java does not look for executables in PATH (like command shell does), you'll have to provide full path to the executable/script that you want to execute (or it has to be in the working directory; you can set the working directory with ProcessBuilder.directory(File) ). 最后,您必须考虑到Java不会在PATH中查找可执行文件(就像命令shell一样),您必须提供要执行的可执行文件/脚本的完整路径(或者必须是在工作目录中;您可以使用ProcessBuilder.directory(File)来设置工作目录。
See also: Difference between ProcessBuilder and Runtime.exec() 另请参阅: ProcessBuilder和Runtime.exec()之间的区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.