如果我用FileReader读取它,我怎么知道我在文件中的位置?

前端之家收集整理的这篇文章主要介绍了如果我用FileReader读取它,我怎么知道我在文件中的位置?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一些像这样的代码

  1. FileReader fr = new FileReader(file);
  2. BufferedReader reader = new BufferedReader(fr);
  3. for (int i=0;i<100;i++)
  4. {
  5. String line = reader.readLine();
  6. ...
  7. }
  8. // at this point I would like to know where I am in the file.
  9. // let's assign that value to 'position'
  10. // then I would be able to continue reading the next 100 lies (this could be done later on ofcourse... )
  11. // by simply doing this:
  12. FileReader fr = new FileReader(file);
  13. fr.skip(position);
  14. BufferedReader reader = new BufferedReader(fr);
  15. for (int i=0;i<100;i++)
  16. {
  17. String line = reader.readLine();
  18. ...
  19. }

我无法弄清楚如何获得/计算’位置’的值.

两件事情:
我显然没有固定长度的文件(即:每行有不同的长度)
我需要让它适用于任何系统(linux,unix,windows),所以我不确定我是否可以假设换行的长度(无论是一个还是两个字符)

任何帮助非常感谢.

谢谢,

最佳答案
如果您可以保持文件打开,可以尝试使用mark()和reset().如果必须关闭文件并重新打开,请尝试FileInputStream.getChannel().position()和FileInputStream.skip()

猜你在找的Java相关文章