java 您可以将扫描仪跳转到文件中的某个位置或向后扫描吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3064373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:10:15  来源:igfitidea点击:

Can you jump a scanner to a location in file or scan backwards?

javajava.util.scanner

提问by Mike

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?

我有一个非常大的文本文件,我需要从接近尾声的某个地方收集数据。也许 Scanner 不是执行此操作的最佳方法,但是在到达我感兴趣的文件部分之前从顶部开始并抓取 6000 行会非常浪费。有没有办法告诉 Scanner 跳转到说文档的 7/8ths 还是从底部开始并逐行向上扫描?

Thanks

谢谢

采纳答案by polygenelubricants

The underlying input source for a java.util.Scanneris a java.lang.Readable. Beyond the Scanner(File)constructor, a Scannerneither knows nor cares of the fact that it's scanning a file.

a 的底层输入源java.util.Scanner是 a java.lang.Readable。除了Scanner(File)构造函数之外,aScanner既不知道也不关心它正在扫描文件的事实。

Also, since it's regex based on java.util.regex.*, there's no way it can scan backward.

此外,由于它是基于 的正则表达式java.util.regex.*,因此无法向后扫描。

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 of Scanner.

要完成您想做的事情,最好在输入源级别执行此操作,例如InputStream.skip在将源传递给Scanner.



On Scanner.skip

Scanner.skip

Scanneritself does have a skip, 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.

Scanner本身确实有一个skip, 并且一个模式"(?s).{10}"会跳过 10 个字符(在(?s)单行/Pattern.DOTALL模式下),但这可能是一种相当迂回的方式。

Here's an example of using skipto skip a given number of lines.

这是skip用于跳过给定行数的示例。

    String text =
        "Line1 blah blah\n" +
        "Line2 more blah blah\n" +
        "Line3 let's try something new \r\n" +
        "Line4 meh\n" + 
        "Line5 bleh\n" + 
        "Line6 bloop\n";
    Scanner sc = new Scanner(text).skip("(?:.*\r?\n|\r){4}");
    while (sc.hasNextLine()) {
        System.out.println(sc.nextLine());
    }

This prints (as seen on ideone.com):

这打印(如在 ideone.com 上看到的):

Line5 bleh
Line6 bloop

回答by RonK

Scannerwraps an InputStream, you can use the stream's skip(long)method to skip the lines you don't want and then start scanning.

Scanner包装一个InputStream,您可以使用流的skip(long)方法跳过您不想要的行,然后开始扫描。

Read more in the InputStreamjavadoc

javadoc 中阅读更多内容InputStream

回答by Ben S

You should probably use RandomAccessFileinstead.

您可能应该改用RandomAccessFile