Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

java - How to set working directory with ProcessBuilder

I am trying start a process in my home directory in ubuntu. I keep getting a permission denied exception and I have no idea why. Here is the code:

Process p = null;
ProcessBuilder pb = new ProcessBuilder("/home");
p = pb.start();

Here is the exception:

Exception in thread "main" java.io.IOException: Cannot run program "/home": 

java.io.IOException: error=13, Permission denied
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:475)
        at tester.Main.main(Main.java:30)
Caused by: java.io.IOException: java.io.IOException: error=13, Permission denied
        at java.lang.UNIXProcess.<init>(UNIXProcess.java:164)
        at java.lang.ProcessImpl.start(ProcessImpl.java:81)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:468)
        ... 1 more
Java Result: 1
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are trying to execute /home and it is not an executable file. The constructor argument of the process builder is the command to execute.

You want to set the working directory. You can that it via the directory method.

Here is a complete example:

Process p = null;
ProcessBuilder pb = new ProcessBuilder("do_foo.sh");
pb.directory(new File("/home"));
p = pb.start();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...