ProcessBuilder cannot run bat file with spaces in path

后端 未结 1 404
挽巷
挽巷 2020-12-04 00:11

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

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

ProcessBuilder pb = new ProcessBuilder(\"cmd\         


        
相关标签:
1条回答
  • 2020-12-04 00:54
    • Don't quote commands in a command list, unless the command been executed expects it, this will just stuff things up
    • user.dir is your programs current executing context...so it actually makes no sense to include it, you could just use midl.bat by itself (assuming the command exists within the current execution context)

    I wrote a really simple batch file...

    @echo off
    dir
    

    Which I put in my "C:\Program Files" directory, as I need a path with spaces and 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 issues...

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