ProcessBuilder cannot run bat file with spaces in path

I have the following segment of code to run a bat file:

String workingDir = System.getProperty("user.dir");

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", 
"\"" + workingDir + File.separator + "midl.bat\"");

Process ddsBuildProc = pb.start();

ddsBuildProc.waitFor();

      

Working Deer includes spaces in the path. Even though I use quotes to wrap the workDir + fileName line, the shell still strips the work Dir and doesn't run the bat file. If trying and copy-paste is to run the bat file path line in a windows command prompt window manually, it works as expected. What could be the problem?

Also, please do not close this question as a duplicate, because I have tried all solutions in other questions without success.

+3


source to share


1 answer


  • Don't list commands in the command list, unless the command was executed, it will just accumulate things
  • user.dir

    - your current executable context of your programs ... so it doesn't really make sense to include it, you can just use midl.bat

    it by itself (assuming the command exists in the current execution context)

I wrote a really simple batch file ...

@echo off
dir

      



Which I entered into the "C: \ Program Files" folder since I need a path with spaces and is used ....

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RunBatch {

    public static void main(String[] args) {
        ProcessBuilder pb = new ProcessBuilder(
                        "cmd", "/c", "listme.bat"
        );
        pb.directory(new File("C:/Program Files"));
        pb.redirectError();
        try {
            Process process = pb.start();
            InputStreamConsumer.consume(process.getInputStream());
            System.out.println("Exited with " + process.waitFor());
        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    public static class InputStreamConsumer implements Runnable {

        private InputStream is;

        public InputStreamConsumer(InputStream is) {
            this.is = is;
        }

        public static void consume(InputStream inputStream) {
            new Thread(new InputStreamConsumer(inputStream)).start();
        }

        @Override
        public void run() {
            int in = -1;
            try {
                while ((in = is.read()) != -1) {
                    System.out.print((char) in);
                }
            } catch (IOException exp) {
                exp.printStackTrace();
            }
        }

    }

}

      

To run it without any problem ...

+4


source







All Articles