2014-01-10 38 views
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循環,當文件到達的結束,當文件追加它開始讀取文件再次留在第二。但是沒有發生,當文件結束時,我的程序等待了一秒鐘,但從不讀取附加在文件中的下一行。

+3

你能簡單地使用unix命令'tail -f'嗎? –

+0

另請參閱:http://stackoverflow.com/questions/557844/java-io-implementation-of-unix-linux-tail-f –

+0

1)對代碼塊使用一致的邏輯縮進。代碼的縮進旨在幫助人們理解程序流程。 2)源代碼中的單個空白行是* always *就足夠了。 '{'之後或'}'之前的空行通常也是多餘的。 –

回答

1
public class LogReader { 
    private static boolean canBreak = false; 

    public static void startReading(String filename) throws InterruptedException, IOException { 
     canBreak = false; 
     String line; 
     try { 
      LineNumberReader lnr = new LineNumberReader(new FileReader(filename)); 
      while (!canBreak) 
      { 
       line = lnr.readLine(); 
       if (line == null) { 
        System.out.println("waiting 4 more"); 
        Thread.sleep(3000); 
        continue; 
       } 
       processLine(line); 
      } 
      lnr.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void stopReading() { 
     canBreak = true; 
    } 

    private static void processLine(String s) { 
     //processing line 
    } 
} 
+1

感謝男人真正的幫助。 :) –