从 Java 进程执行时跳过批处理文件中的暂停命令

Skipping a pause command in a batch file when executing from a Java Process

抱歉,如果这是重复的,但没有其他解决方案有效。

我正在尝试编写一个 Java 应用程序,它将调用一个批处理文件,打印出批处理文件正在做什么,并等待它完成执行,然后再做任何其他事情。我读过通过 Process.getOutputStream() 发送换行符会触发 "Press any key to continue..." 提示,但它不适合我。

这是我的 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

这是我的 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();
    }
}

在 while 循环中,它会打印出:

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...

永远不要传递暂停语句。我试过重定向错误输出、发送 VK_ENTER 和发送随机密钥都无济于事。

有什么想法吗?

对于缓冲写入器,您必须在它们实际写入之前刷新缓冲区。在 out.write() 之后调用 out.flush()。