简体   繁体   English

将Runtime.exec()与字符串[]一起使用

[英]Using Runtime.exec() with String [ ]

I am trying to execute a bash script that gets passed 4 arguments from java. 我正在尝试执行从Java传递4个参数的bash脚本。 I can execute the script without the arguments perfectly using this code: 我可以使用以下代码完美地执行脚本,而无需使用参数:

  try { String command = "bash bash/testbash.sh"; Runtime run = Runtime.getRuntime(); Process pr = run.exec(command); pr.waitFor(); BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while ((line=buf.readLine())!=null) { System.out.println(line); } } catch (Exception e) { System.out.println("Exception " + e); e.printStackTrace(); } } 

So I was going to make a String[] to pass both the commands and the arguments to Runtime.exec(), like so: 所以我要制作一个String [],将命令和参数都传递给Runtime.exec(),如下所示:

  try { String[] command ={"bash bash/testbash.sh"}; Runtime run = Runtime.getRuntime(); Process pr = run.exec(command); pr.waitFor(); BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while ((line=buf.readLine())!=null) { System.out.println(line); } } catch (Exception e) { System.out.println("Exception " + e); e.printStackTrace(); } } 

which gives me this error: 这给了我这个错误:

 Exception java.io.IOException: Cannot run program "bash bash/testbash.sh": error=2, No such file or directory java.io.IOException: Cannot run program "bash bash/testbash.sh": error=2, No such file or directory at java.lang.ProcessBuilder.start(ProcessBuilder.java:1042) at java.lang.Runtime.exec(Runtime.java:615) at java.lang.Runtime.exec(Runtime.java:483) at bashExecuter.main(bashExecuter.java:43) Caused by: java.io.IOException: error=2, No such file or directory at java.lang.UNIXProcess.forkAndExec(Native Method) at java.lang.UNIXProcess.<init>(UNIXProcess.java:135) at java.lang.ProcessImpl.start(ProcessImpl.java:130) at java.lang.ProcessBuilder.start(ProcessBuilder.java:1023) ... 3 more 

this makes no sense to me. 这对我来说毫无意义。 The bash file clearly exists because I just used it with the String command, but when I use the same thing with String[] command its not there? bash文件显然存在,因为我只是将其与String命令一起使用,但是当我将相同的东西与String []命令一起使用时,它不在吗? How would I pass the command with arguments? 如何传递带有参数的命令?

String []命令= {“ bash bash / testbash.sh”};

String[] command ={"bash", "bash/testbash.sh"};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM