Java 8 在JVM内创建文件时,commons io Tailer没有调用handle()
我有一个有效的Tailer实现 这是我的零售商:Java 8 在JVM内创建文件时,commons io Tailer没有调用handle(),java-8,apache-tailer,Java 8,Apache Tailer,我有一个有效的Tailer实现 这是我的零售商: public class SyslogConsumer implements TailerListener { @Override public void handle(String line) { System.out.println(line);} ... } public void process() { TailerListener listener = new SyslogConsumer();
public class SyslogConsumer implements TailerListener {
@Override
public void handle(String line) { System.out.println(line);}
...
}
public void process() {
TailerListener listener = new SyslogConsumer();
final Tailer tailer = Tailer.create( path.toFile(), listener );
Runtime.getRuntime().addShutdownHook( new Thread( "LogProcessor shutdown hook" ) {
public void run() {
tailer.stop();
}
} );
}
还有我的测试:
public class LogProcessorTest {
private static Path templog;
private static final String logEvent = "May 1 00:00:00 this is valid";
@Before
public void setup()
throws IOException
{
templog = Files.createTempFile( "logprocessing", ".log" );
templog.toFile().deleteOnExit();
BufferedWriter bw = new BufferedWriter( new FileWriter( templog.toFile() ) );
bw.write( logEvent );
bw.newLine();
bw.close();
}
@Test
public void testProcessingValidEntriesProducesEvents()
throws IOException
{
// utility method that pipes stdout to my bytearray
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TestUtils.captureStdOut( bos );
LogProcessor proc = new LogProcessor( templog.toString() );
proc.process();
String s = bos.toString( "UTF-8" );
Assert.assertEquals( logEvent, s );
}
}
在对bos进行内容自检时,bos为空,但日志文件包含两行:
>May 1 00:00:01 this is valid
>
如果我将测试指向使用bash脚本创建并写入的文件:
$ cat test/endlessLogGenerator.sh
#! /bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
out="$DIR/data/logstream.out"
echo > $out
c=0
while :
do
let c=$((c+1))
echo $(date +"%b %d %T this is message $c") >> $out
sleep 1
done
然后它就完美地工作了。然而,当我在测试运行程序中创建文件时,我的侦听器从未被Tailer处理程序调用。我试着在一个单独的线程中创建我的文件,也试着写入一个不是由测试创建的现有文件,还试着在将文件交给Tailer查看后在测试中写入该文件,等等。没有任何效果。我在测试运行程序中写入文件的尝试似乎不会导致TailerListener触发handle方法。我在Windows7和Java8上运行这个,在Eclipse中。有没有人有过使用运行测试的JVM写入的文件对TailerListener的handle方法进行单元测试的经验
谢谢。我发现我的问题是因为零售商吞下了一个异常,然后默默地关闭了流:
Tailer's run() implementation...
....
} catch (Exception e) {
listener.handle(e);
} finally {
IOUtils.closeQuietly(reader);
}
....
在我的handle实现中,我正在解析日志中的日期,DateTimeFormatter没有使用正确的模式设置,因此它抛出了一个未经检查的运行时异常,这被Tailer捕获。库实现者设计这种行为的奇怪选择
我保留这个问题,而不是仅仅删除它,因为这个警告可能会派上用场