3
我在应用程序中有非常不同的场景。我需要阅读一些文本文件并做一些工作。连续读取文件
其实我想要的是,当我到达行尾时,我在Java中读取光标的文件将停在那里并等待直到新行附加到文本文件中。实际上我正在阅读的文件是由服务器生成的实时日志,日志会在每秒钟后生成。
所以我希望我的文件读取过程永远不会结束,随着新数据进入文件,它会继续读取文件。
我写了这个代码,
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
{
String i = sc.nextLine();
processLine(i); //a method which do some stuff on the line which i read
if(thread==1)
{
System.out.print("After loop in the file"); //just for printing
}
while(!(sc.hasNextLine())) //in the loop until new line comes
{
System.out.println("End of file");
Thread.sleep(100000);
System.out.println("Thread is waiting");
thread++;
}
if(thread==1)
{
System.out.println("OUt of the thread");
}
//System.out.println(i);
}
sc.close();
System.out.println("Last time stemp is "+TimeStem);
System.out.println("Previous Time Stemp is "+Previous_time);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
这是我的代码,我想我的计划将while循环,当文件到达的结束,当文件追加它开始读取文件再次留在第二。但是没有发生,当文件结束时,我的程序等待了一秒钟,但从不读取附加在文件中的下一行。
你能简单地使用unix命令'tail -f'吗? –
另请参阅:http://stackoverflow.com/questions/557844/java-io-implementation-of-unix-linux-tail-f –
1)对代码块使用一致的逻辑缩进。代码的缩进旨在帮助人们理解程序流程。 2)源代码中的单个空白行是* always *就足够了。 '{'之后或'}'之前的空行通常也是多余的。 –