Search code examples
javafilebatch-filecommandpiping

Does running a batch file from java program destroy piping?


I'm trying to run a batch file from within my Java program, but I'm getting some strange behavior.

Process p = Runtime.getRuntime().exec("cmd /c start temp.bat");

This usually runs okay, but I've found that piping commands in the batch file won't work. Any suggestions?


Solution

  • I advise you to use CommonsExec which will make your life a lot easier. You could use some code like this (untested):

    CommandLine cmdLine = new CommandLine("ping");
    cmdLine.addArgument( host );
    
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler     psh    = new PumpStreamHandler( stdout );
    
    DefaultExecutor executor = new DefaultExecutor(); 
    executor.setStreamHandler( psh );
    
    try {
      executor.execute( cmdLine );
    } catch ( Exception e ) {
    }
    
    System.out.println( stdout.toString() );