I am trying to execute a bash script file , for a java program it the following way :
Runtime.getRuntime().exec("./path/to/bash");
But it seems to be not the correct way for doing it because it return the following exception:
java.io.IOException: Cannot run program "./path/to/bash": error=2, No such file or directory
what is the correct way to do it ?
java.io.IOException: Cannot run program "./path/to/bash": error=2, No such file or direct
It mean path of file was wrong. Please check file path again. What folder contains this file?
要使用Java执行任何bash命令,可以使用Runtime.getRuntime().exec("/path-to/bash -c \\"rm *.foo\\"")
-这将删除所有具有扩展名的文件.foo
当前工作目录中的.foo
Recently I used the below approach to execute a bash script.
Process exec = getRuntime().exec("/home/user/test/test.sh");
java.util.Scanner s = new java.util.Scanner(exec.getInputStream()).useDelimiter("\\A");
System.out.println(s.next());
Whenever I tried getRuntime().exec("./home/user/test/test");
I got the exact error you were getting. java.io.IOException: Cannot run program "./home/user/test/test": error=2, No such file or directory
. To execute any command from any directory, please follow the below approach.
String []command ={"/bin/bash","-c", "ls"};
Process exec = getRuntime().exec(command,null,new
File("/home/user/test"));
java.util.Scanner s = new java.util.Scanner(exec.getInputStream()).useDelimiter("\\A");
System.out.println(s.next());
Hope this is some way helpful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.