我有一个类,我可以在其中从 shell 脚本运行 rsync 命令。
一切正常,除了将过程输出(流内和错误流)记录到文件时。
我的类中有一个循环,如果进程失败,它允许运行 5 次,并且在每次运行中,每个流/写入器/读取器都被初始化并完全关闭。
问题是文件在 5 次运行中只被写入一次或两次,而且输出的永远不是相同的运行。我在该过程之后设置了 10 秒的 sleep 时间以使输出更具可读性,并且我可以看到写入文件的唯一输出是在 20 秒和 30 秒之后,或者 10 秒和 40 秒等之后。
进程的每个输出都写入控制台而不是文件。
我的代码如下。任何建议将不胜感激。
private static void run() throws IOException {
while (retry && NUMBER_OF_TRIES >= tries){
InputStream in = null;
PrintStream out = null;
InputStream errIn = null;
try {
// get runtime object to run cmd
Runtime RT = Runtime.getRuntime();
Process PR = RT.exec( cmd );
errIn = PR.getErrorStream();
in = PR.getInputStream();
out = new PrintStream(new FileOutputStream(new File(output), true));
System.out.println("file output initialised");
StreamGobbler inConsumer = new StreamGobbler( in, new Date() + " OUTPUT: ", out );
StreamGobbler errConsumer = new StreamGobbler( errIn, new Date() + " ERROR: ", out );
System.out.println("Starting consumer threads");
inConsumer.start();
errConsumer.start();
Thread.sleep(10000);
int exitVal = PR.waitFor();
if (exitVal > 0){
retry = true;
tries++;
} else {
retry = false;
}
System.out.println("ExitValue: " + exitVal);
// Wait for the consumer threads to complete
inConsumer.join();
errConsumer.join();
} catch ( Exception e ) {
e.printStackTrace();
System.out.println( "failed: " + e.getMessage() );
} finally {
// the StreamConsumer classes will close the other streams
if ( out != null ){
out.close();
}
if (in != null){
in.close();
}
if (errIn != null){
errIn.close();
}
}
}
}
最佳答案
除了初始化之外,我从来没有看到你的打印流对象“out”被使用过。如果你想写入文件,你应该调用 printstream 对象。
System.out.println("ExitValue: " + exitVal);
//now call the printstream object
out.print("ExitValue: " + exitVal);
//flushing will force the string to be written to the file
out.flush();
每次写入控制台时都可以按照上面的代码进行操作,并且希望写入创建打印流对象所用的文件。
关于java - 进程循环运行而不是每次都记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40047100/