简体   繁体   English

在 Java 中通过分隔符行拆分文件

[英]Split a file by delimiter line in Java

Say, I have a file which looks as follows:说,我有一个如下所示的文件:

---------
line11
line12
line13
---------
line21
line22
line23
line24
line25
---------
line31
line32
---------

And I need to split a list of lines from this file into sublists delimited by line contains dash symbols and process them separately.我需要将此文件中的行列表拆分为由包含破折号的行分隔的子列表,并分别处理它们。 Is there any handy way to do that in Java?在 Java 中有什么方便的方法可以做到这一点吗?

A quick way is using the Scanner class.一种快速的方法是使用 Scanner 类。 Specify a custom "delimiter", and it will return you chunks of lines.指定一个自定义的“分隔符”,它会返回你的行块。

    Scanner scanner = new Scanner(new File("file.txt"));
    scanner.useDelimiter("---------");
    while (scanner.hasNext()) {
        System.out.println("<<<<" + scanner.next() + ">>>>>");
    }

Output:输出:

<<<<
line11
line12
line13
>>>>>
<<<<
line21
line22
line23
line24
line25
>>>>>
<<<<
line31
line32
>>>>>

As @MadProgrammer has already mentioned, the algorithm would be if (input.equals("---------")) { /* create new sublist */ } .正如@MadProgrammer 已经提到的,算法将是if (input.equals("---------")) { /* create new sublist */ } There will be a few validations which are straight forward.将有一些直接的验证。 Feel free to comment in case of any doubt/issue.如有任何疑问/问题,请随时发表评论。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String line;
        List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
        List<String> sublist = new ArrayList<String>();
        int row = 1;
        try {
            Scanner reader = new Scanner(new File("file.txt"));
            while (reader.hasNextLine()) {
                line = reader.nextLine();
                if (line != null && row != 1 && line.equals("---------")) {
                    list.add(new ArrayList<String>(sublist));
                    sublist = new ArrayList<String>();
                } else {
                    if (!line.equals("---------")) {
                        sublist.add(line);
                    }
                    row++;
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("Error: unable to read file.");
        }
        System.out.println(list);
    }
}

Output:输出:

[[line11, line12, line13], [line21, line22, line23, line24, line25], [line31, line32]]

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

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