如何从文件中获取新内容 [英] How to get the new content from the file

查看:114
本文介绍了如何从文件中获取新内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:

1.创建fromX.txt和to.txt文件(内容必须附加,将来自另一个逻辑)
2。如果是,请将每个秒从.xxt文件中检查新添加到toY.txt

1.Create fromX.txt and toY.txt file (content has to be appended and will come from another logic) 2.check every second fromX.txt file for new addition if yes write it to toY.txt

如何从X.txt文件中获取新的内容?

how to get the just new content fromX.txt file?

我尝试通过计算行数并寻找任何变化来实现它。

I have tried implementing it by counting number of lines and looking for any change in it.

public static int countLines(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}


推荐答案

你实现它如下:


  1. 打开使用 RandomAccessFile

  2. 寻找上次文件结尾的位置。 (如果这是第一次,请寻找文件的开头。)

  3. 阅读,直至到达新的文件结尾。

  4. 记录文件结尾的位置。

  5. 关闭 RandomAccessFile

  1. Open the using RandomAccessFile
  2. Seek to where the end-of-file was last time. (If this is the first time, seek to the start of the file.)
  3. Read until you reach the new end-of-file.
  4. Record where the end-of-file is.
  5. Close the RandomAccessFile

将位置记录为距文件开头的字节偏移量,并使用相同的值进行搜索。

Record the position as a byte offset from the start of the file, and use the same value for seeking.

您可以修改上述内容以重复使用 RandomAccessFile 对象,而不是每次都打开/关闭它。

You can modify the above to reuse the RandomAccessFile object rather than opening / closing it each time.

UPDATE - RandomAccessFile 的javadoc是这里。寻找 seek getFilePointer 方法。

UPDATE - The javadocs for RandomAccessFile are here. Look for the seek and getFilePointer methods.

这篇关于如何从文件中获取新内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆