抱歉,如果这是重复的,但没有其他解决方案。
我正在尝试编写一个Java应用程序,该应用程序将调用批处理文件,打印出该批处理文件在做什么,然后等待其完成执行,然后再执行其他操作。我已经读过,通过Process.getOutputStream()发送换行会触发“按任意键继续...”提示,但它对我而言并不是这样做。
这是我的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驱动程序:
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()。
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras