changing the working-directory of command from java

家住魔仙堡 提交于 2019-11-26 20:55:21

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.

Ray Tayek

Use this form of the exec method to specify a working directory

public Process exec(String[] cmdarray,
                    String[] envp,
                    File dir)
             throws IOException

The working directory is the third argument. You can pass null for envp if you don't need to set any special environment.

There's also this convenience method:

public Process exec(String command,
                    String[] envp,
                    File dir)
             throws IOException

...where you specify the command in one string (it just gets turned into an array for you; see the docs for details).

David Hazani

I goted a same problem in my project, I tryed this solutions about ProcessBuilder.directory(myDir) and the exec method from Runtime and all my trays failed..
It's make me understanding that the Runtime have a limited privileges just for the working directory and the sub directories of it.

So my solution is ugly but working very well.
I create a temporary .bat file in "runtime" in the working directory.
This file included two lines of commands:
1. Move to needed directory (cd command).
2. Do the command in need.
I call the exec from Runtime with my temporarily .bat file as command.
It's work for me very well!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!