How do I Pipe process output to a file on Windows and JDK 6u45

后端 未结 3 1607
悲&欢浪女
悲&欢浪女 2021-01-17 19:00

I have the following windows batch file (run.bat):

@echo off
echo hello batch file to sysout

And the following java code, which runs the ba

3条回答
  •  半阙折子戏
    2021-01-17 19:22

    Several suggestions here:

    • Does the input with the spaces need to be treated as single String (with spaces),or id it in actual several inputs? If the first Option is the case I would suggest to quote it for the windows runtime:

    ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", 
    "run.bat", "\"Some Input With Spaces\"", 
    ">>", "stdout.txt","2>>", "stderr.txt");
    
    • Instead of redirecting the input to stdout.txt and stderr.txt using the shell, why not do it using Java using getOutputStream() and getErrorStream()? Here is an example using Guava's IO package. Of course you may want to have those in separate threads, you need proper exception handling, etc.

    InputStream stdout = new BufferedInputStream(proc.getInputStream());
    FileOutputStream stdoutFile = new FileOutputStream("stdout.txt");
    ByteStreams.copy(stdout, stdoutFile);
    
    InputStream stderr = new BufferedInputStream(proc.getErrorStream());
    FileOutputStream stderrFile = new FileOutputStream("stderr.txt");
    ByteStreams.copy(stderr, stderrFile);
    
    stdout.close();
    stderr.close();
    stdoutFile.close();
    stderrFile.close();
    
    • Another option, why not create a run.bat wrapper that will make the redirections?

    @echo off
    cmd.exe /c run.bat "%1" >> "%2" 2>> "%3"
    

提交回复
热议问题