Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scanner "rewind"

Tags:

java

parsing

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)?

Many thanks, Thomas

EDIT:

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.

like image 945
Tom Avatar asked Sep 19 '26 12:09

Tom


1 Answers

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.

like image 75
Hovercraft Full Of Eels Avatar answered Sep 22 '26 01:09

Hovercraft Full Of Eels