场景:
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(); } }推荐答案
你实现它如下:
将位置记录为距文件开头的字节偏移量,并使用相同的值进行搜索。
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.
更多推荐
如何从文件中获取新内容
发布评论