I am trying to exec some Mac’s (linux’s?) commands from Java code. I have made this short class as an example. I tried reading other similar questions on this forum but couldn’t fix it.
It gives me error.
I tried:
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("/Users/xxxx/Documents/ABC");
Access denied message comes up. and the code below gives error.
This question
Want to invoke a linux shell command from Java
has talked about similar problem but I don’t think they ended their debate.
I am using mac os 10.7.
public class Main {
public static void main(String args[]) {
try {
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /Users/xyz/Documents/ABC"});
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = p.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}
I used the full path “/bin/bash” and used a different directory and it works perfectly fine. So the code is almost correct. You just need to be careful with the path, directory permissions and might want to use the full path. Really appreciate your support guys. cheers