如何从文件中获取新内容

编程入门 行业动态 更新时间:2024-10-14 08:29:57
本文介绍了如何从文件中获取新内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

场景:

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(); } }

推荐答案

你实现它如下:

  • 打开使用 RandomAccessFile
  • 寻找上次文件结尾的位置。 (如果这是第一次,请寻找文件的开头。)
  • 阅读,直至到达新的文件结尾。
  • 记录文件结尾的位置。
  • 关闭 RandomAccessFile
  • Open the using RandomAccessFile
  • Seek to where the end-of-file was last time. (If this is the first time, seek to the start of the file.)
  • Read until you reach the new end-of-file.
  • Record where the end-of-file is.
  • 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.

    更多推荐

    如何从文件中获取新内容

    本文发布于:2023-11-25 23:09:57,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1631722.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:文件   内容

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!