How to Set Working Directory with Processbuilder

How to set working directory with ProcessBuilder

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();

Setting working directory for ProcessBuilder is not working

Use below code :

        String fileToOpen = "test.pdf";
List<String> command = new ArrayList<String>();
command.add("rundll32.exe");
command.add("url.dll,FileProtocolHandler");
command.add(fileToOpen);

ProcessBuilder builder = new ProcessBuilder();
builder.directory(new File("C://Software//"));
builder.command(command);

builder.start();

It will open your pdf .

Just change the file name if you want to open other file in same directory.

Change the working drive java processbuilder

Edit: ProcessBuilders directory(File) method returns a new ProcessBuilder so try pb=pb.directory(new File("...)

crude way would be to export the command to a batchfikle in the same dir as your project and putting the change drive code into the batch file, too and then run the batch file from your code.

Example that changes from a directory on C to a directory on D; (i have my NetBeans installation and the project-directory on the C-Drive)

ProcessBuilder pb = new ProcessBuilder("cmd.exe","/c","start","cmd");
pb=pb.directory(new File("D:\\src"));
pb.start();

How to restrict directory with ProcessBuilder?

That's not possible - ProcessBuilder simply executes programs on your computer, it doesn't run them in a sandbox.

ProcessBuilder#directory(File) sets the working directory for the process.

changing the working-directory of command from java

To implement this you can use the ProcessBuilder class, here's how it would look like:

File pathToExecutable = new File( "resources/external.exe" );
ProcessBuilder builder = new ProcessBuilder( pathToExecutable.getAbsolutePath(), "-i", "input", "-o", "output");
builder.directory( new File( "resources" ).getAbsoluteFile() ); // this is where you set the root folder for the executable to run with
builder.redirectErrorStream(true);
Process process = builder.start();

Scanner s = new Scanner(process.getInputStream());
StringBuilder text = new StringBuilder();
while (s.hasNextLine()) {
text.append(s.nextLine());
text.append("\n");
}
s.close();

int result = process.waitFor();

System.out.printf( "Process exited with result %d and output %s%n", result, text );

It's quite a bunch of code, but gives you even more control on how the process is going to be run.



Related Topics



Leave a reply



Submit