您可以将扫描仪跳到文件中的某个位置还是向后扫描? [英] Can you jump a scanner to a location in file or scan backwards?

查看:104
本文介绍了您可以将扫描仪跳到文件中的某个位置还是向后扫描?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的文本文件,我需要从结尾处收集数据.也许Scanner并不是执行此操作的最佳方法,但是在到达我感兴趣的文件部分之前,先从顶部开始并抓住6000行非常浪费.是否有办法告诉Scanner跳转至是说要向下7/8英寸,还是要从底部开始,然后逐行向上扫描?

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?

谢谢

推荐答案

java.util.Scanner的基础输入源是

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

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

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

要完成您想做的事情,最好在输入源级别执行此操作,例如通过使用 InputStream.skip 源代码,然后再将其传递给Scanner的构造函数.

To accomplish what you want to do, it's best to do it at the input source level, e.g. by using InputStream.skip of the source before passing it to the constructor of Scanner.

Scanner本身确实具有的模式将跳过10个字符(在(?s)单行/

Scanner itself does have a skip, and a pattern like "(?s).{10}" would skip 10 characters (in (?s) single-line/Pattern.DOTALL mode), but this is perhaps a rather roundabout way of doing it.

下面是使用skip跳过给定行数的示例.

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

    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());
    }

此打印(如在ideone.com上看到的那样 ):

This prints (as seen on ideone.com):

Line5 bleh
Line6 bloop

这篇关于您可以将扫描仪跳到文件中的某个位置还是向后扫描?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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