【问题标题】:Continuous File reading [duplicate]连续文件读取[重复]
【发布时间】:2014-01-29 01:16:17
【问题描述】:

我的应用程序中有非常不同的场景。我需要阅读一些文本文件并为此做一些工作。

实际上我想要的是,当我到达行尾时,我在 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吗?
  • 1) 对代码块使用一致且符合逻辑的缩进。代码的缩进是为了帮助人们理解程序流程。 2) 源代码中的一个空白行总是就足够了。 { 之后或 } 之前的空行通常也是多余的。
  • 第二个while循环是什么意思?我看不到任何第二个 while 循环。
  • 你真的要让线程休眠 100 秒吗?

标签: java file loops eof


【解决方案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
    }
}

【讨论】:

  • 感谢他的真正帮助。 :)
猜你喜欢
  • 2011-04-17
  • 2015-07-21
  • 2020-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多