changing the working-directory of command from java

后端 未结 3 1103
失恋的感觉
失恋的感觉 2020-11-27 07:28

I need to execute a .exe file from a function in one of the packages I have in my java project. now the working directory is the root directory of the project for java but t

相关标签:
3条回答
  • 2020-11-27 08:10

    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!

    0 讨论(0)
  • 2020-11-27 08:16

    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).

    0 讨论(0)
  • 2020-11-27 08:18

    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.

    0 讨论(0)
提交回复
热议问题