简体   繁体   English

解析多行文本文件的单行?

[英]Parsing Individual Lines of Multi-Line Text File?

I have a question about something I've done in the past, but never really thought if it was the most efficient method to use. 我对过去所做的事情有疑问,但从未真正想到这是否是最有效的方法。

Let's say I have a text file, where each line contains something important and let's then say I have multiple sets of these lines, each corresponding to a unique environment...so for example: 假设我有一个文本文件,其中每行包含一些重要内容,然后说我有多组这些行,每组对应于一个独特的环境...因此,例如:

1
String that I need to parse for specific tokens..
2
String that I need to parse for specific tokens..
String that I need to parse for specific tokens..
3
String that I need to parse for specific tokens..
String that I need to parse for specific tokens..
String that I need to parse for specific tokens..

So given the above input file, my past way of solving this would be something similar to the following (semi-pseudocode!): 因此,鉴于上述输入文件,我过去解决此问题的方式将类似于以下内容(半伪代码!):

BufferedReader inputFile = new BufferedReader(new FileReader("file.txt"));
while(inputFile.hasNextLine())
{    
     Scanner line = new Scanner(inputFile.nextLine());
     //parse the line looking for tokens

}

inputFile.close();

My issue with this is it seems incredibly inefficient to create a new Scanner object for every line I have in my BufferedReader. 我的问题是,为BufferedReader中的每一行创建一个新的Scanner对象似乎效率很低。

Is there a better way to achieve this functionality? 有没有更好的方法来实现此功能?

One suggestion may be to scan the whole document by tokens, but my issue with that is I won't be able to keep track of how many strings are apart of the subset (indicated by the integer); 一种建议可能是用标记扫描整个文档,但是我的问题是我无法跟踪子集中有多少个字符串(用整数表示); or at least I can't think of another solution to that other than to decrement a counter every time I look at a new line. 至少我每次想到换行时都要减少计数器,否则至少我想不出另一种解决方案。

Thanks in advance! 提前致谢!

check out with this; 签出这个;

public static void main(String[] args) throws IOException {

        BufferedReader bf = new BufferedReader(new FileReader(new File("d:/sample.txt")));
        LineNumberReader lr = new LineNumberReader(bf);
        String line = "";            
        while ((line = lr.readLine()) != null) {
            System.out.println("Line Number " + lr.getLineNumber() +
                    ": " + line);                
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM