Reputation: 115
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 ?
Upvotes: 0
Views: 5215
Reputation: 588
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.
Upvotes: 1
Reputation: 1037
To execute any bash command using java , you can use command like Runtime.getRuntime().exec("/path-to/bash -c \"rm *.foo\"")
- This will remove all the files having extension .foo
in the current working directory
Upvotes: 1
Reputation: 97
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?
Upvotes: 2