Java扫描器“倒带" [英] Java Scanner "rewind"

查看:48
本文介绍了Java扫描器“倒带"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java扫描器对象来解析文本文件.我将需要对文件的一部分进行两次扫描(出于性能方面的考虑,这样就不必临时存储其内容了.)

I'm using a Java Scanner object to parse a text file. I would need to scan part of the file twice (for performance reasons so that I don't have to store its content temporarily).

因此,有没有一种方法可以将扫描仪倒带"到特定的文件位置?

Hence, is there an approach to "rewind" the Scanner to a specific file position?

或者,有没有一种方法可以克隆扫描仪,以便我可以独立使用每个实例(即它们不会移动彼此的文件位置指针)?

Alternatively, is there a way to clone a scanner so that I can use independently each instance (i.e. they will not move each other's file position pointer)?

非常感谢,托马斯

仅扫描一次文件并直接对其进行处理显然总是可能的,但是这将在我们现有的代码库中带来极大的额外复杂性,因此需要对文件的同一部分进行两次扫描.

Scanning the file only once and processing it directly is obviously always possible but would create significant additional complexity in our existing code base, hence the need to scan twice the same portion of the file.

简而言之:该文件包含数千个逻辑项,并且要处理其中的一些逻辑项,我需要从该项开始将一个信息存储在该项的末尾.

In a nutshell: the file contains thousands of logical items and to process some of them, I need to have from the item start an info that is stored at the end of the item.

推荐答案

仅在需要时创建一个新的Scanner实例.即使有可能,克隆它也没有必要或好处.与重绕"相同-如果您需要重新读取文件,只需创建一个新的扫描仪.我会探索如何存储所需的位,因为我确信这会更有效.

Just create a new Scanner instance when you need one. There's no need or benefit to cloning it even if you could. Same for "re-winding" -- just create a new Scanner if you need to re-read the file. I would explore however storing the bits you need, as I'm sure that this would be more efficient.

顺便说一句:考虑向我们介绍您的要求以及任何限制背后的原因,因为这些信息可以帮助我们为您提供更好的答案.

As an aside: consider telling us more about your requirements and the reasoning behind any restrictions as this information can help us give you better answers.

这篇关于Java扫描器“倒带"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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