如何从java扫描仪获取文件中的位置(字节位置)?
如何从java扫描仪获取文件中的位置(字节位置)?
Scanner scanner = new Scanner(new File("file"));
scanner.useDelimiter("abc");
scanner.hasNext();
String result = scanner.next();
现在:如何获取文件中结果的位置(以字节为单位)?
使用scanner.match().start()不是答案,因为它给出了内部缓冲区内的位置。
How to obtain a position in file (byte-position) from the java scanner?
Scanner scanner = new Scanner(new File("file"));
scanner.useDelimiter("abc");
scanner.hasNext();
String result = scanner.next();
and now: how to get the position of result in file (in bytes)?
Using scanner.match().start() is not the answer, because it gives the position within internal buffer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它可能使用 RandomAccessFile.. 尝试这个..
Its possibe using RandomAccessFile.. try this..
Scanner
提供了对底层Readable
的抽象,其内容不一定来自File
。它不直接支持您正在寻找的那种低级查询。您也许可以通过根据
Scanner
结合内部缓冲区位置和根据Readable
读取的字节数来计算这个数字,但即使这看起来也是一个棘手的提议。如果大文件中的大致位置是可以接受的,那么这可能就足够了。Scanner
provides an abstraction over the underlyingReadable
, whose content need not necessarily come from aFile
. It doesn't directly support the kind of low-level query that you're looking for.You may be able to compute this number by combining the internal buffer position according to the
Scanner
and the number of bytes read according to theReadable
, but even this looks to be a tricky proposition. If an approximate location within a huge file is acceptable, then this may be good enough.您可以通过使用自定义 FileInputStream 创建 Scanner 来获得大致的文件位置,如下所示:
这将为您提供精确到 8K 左右的位置,具体取决于 FileInputStream 的实现。这对于在文件解析期间更新进度条之类的事情很有用,其中
你不需要确切的位置,只需要相当接近的位置。
You can get an approximate file position by using a custom FileInputStream to create the Scanner, like this:
This will give you a position accurate to within 8K or so, depending on the implementation of FileInputStream. This is useful for things like updating progress bars during a file parse, where
you don't need the exact position, just something reasonably close.