I have a very large text file and I need to gather data from somewhere near the end. Maybe Scanner isn’t the best way to do this but it would be very wasteful to start at the top and grab 6000 lines before getting to the part of the file I am interested in. Is there a way to either tell Scanner to jump to say 7/8ths down the document or start from the bottom and scan upwards grabbing line by line?
Thanks
The underlying input source for a
java.util.Scanneris ajava.lang.Readable. Beyond theScanner(File)constructor, aScannerneither knows nor cares of the fact that it’s scanning a file.Also, since it’s regex based on
java.util.regex.*, there’s no way it can scan backward.To accomplish what you want to do, it’s best to do it at the input source level, e.g. by using
InputStream.skipof the source before passing it to the constructor ofScanner.On
Scanner.skipScanneritself does have askip, and a pattern like"(?s).{10}"would skip 10 characters (in(?s)single-line/Pattern.DOTALLmode), but this is perhaps a rather roundabout way of doing it.Here’s an example of using
skipto skip a given number of lines.This prints (as seen on ideone.com):