Sorry if this is a duplicate, but no other solution has worked.
I'm trying to write a Java app that will call a batch file, print out what the batch file is doing, and wait for it to finish execution, then do whatever else. I've read that sending a linefeed through Process.getOutputStream() would trigger the "Press any key to continue..." prompt, but it's not doing it for me.
Here's my test.bat:
@echo off
echo This is a test batch file.
echo This text should be readable in the console window
echo Pausing...
pause
echo done.
exit
And here is my Java driver:
public class Tester {
String cmd[] = { "cmd", "/c", "C:/Test Folder/test.bat" };
BufferedReader in = null;
BufferedWriter out = null;
Process p = null;
public Tester() {
System.out.println( "Starting process..." );
ProcessBuilder pb = new ProcessBuilder( cmd ).redirectErrorStream( true );
try {
p = pb.start();
System.out.println( "Started process " + p.hashCode() );
in = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
out = new BufferedWriter( new PrintWriter( p.getOutputStream() ) );
String line = "";
while ( ( line = in.readLine() ) != null ) {
System.out.println( "INFO [" + p.hashCode() + "] > " + line );
// Wait for "Press any key to continue . . . from batch"
if ( line.startsWith( "Press" ) ) {
System.out.println( "INFO [ SYS ] > Script may have called PAUSE" );
out.write( "\n\r" );
}
}
int e = p.waitFor();
if ( p.exitValue() != 0 )
System.err.println( "Process did not finish successfully with code " + e );
else
System.out.println( "Process finished successfully with code " + e );
} catch ( IOException ioe ) {
System.err.println( "I/O: " + ioe.getMessage() );
} catch ( InterruptedException ie ) {
System.err.println( "Interrupted: " + ie.getMessage() );
} catch ( Exception e ) {
System.err.println( "General Exception: " + e.getMessage() );
} finally {
try {
in.close();
out.close();
p.destroy();
} catch ( Exception e ) {
System.err.println( "Error closing streams: " + e.getMessage() );
}
}
System.out.println( "Tester has completed" );
}
public static void main( String[] args ) {
new Tester();
}
}
In the while loop, it'll print out:
Starting process...
Started process 2018699554
INFO [2018699554] > This is a test batch file.
INFO [2018699554] > This text should be readable in the console window
INFO [2018699554] > Pausing...
And never go pass the pause statement. I've tried redirecting error output, sending VK_ENTER, and sending random keys all to no avail.
Any ideas?
With buffered writers, you have to flush the buffer before they actually write. Call out.flush() after out.write().