0

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();
        }
    }
}
Community
  • 1
  • 1
Achilles
  • 711
  • 2
  • 13
  • 35
  • Does the process have appropriate permissions to view the object? – Ignacio Vazquez-Abrams Jul 22 '12 at 01:42
  • If I run it as myself, pointed to a file that I own, it runs and exits without error. – Paul Tomblin Jul 22 '12 at 01:43
  • 3
    Please edit your post and add the _complete_ stack trace that is produced. – Jim Garrison Jul 22 '12 at 01:44
  • Yes it should have the permission as I can access the directory from the terminal just from this code – Achilles Jul 22 '12 at 01:49
  • It only prints "Exited with error code 1" – Achilles Jul 22 '12 at 01:53
  • 1
    Your code works fine for me. You might try using the full path `"/bin/bash"` instead of just `"bash"`, but otherwise I can't think of a good reason why this wouldn't work. – Greg Hewgill Jul 22 '12 at 02:39
  • 1
    Perhaps you could add an answer to this question that describes the solution so that other people who have the same question can learn from this too. – Greg Hewgill Jul 22 '12 at 02:50
  • @GregHewgill Thank you mate, I tried but I have to wait 8 ours before I can answer to my own question. But here it is "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" – Achilles Jul 22 '12 at 02:55

1 Answers1

0

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

Achilles
  • 711
  • 2
  • 13
  • 35