简体   繁体   中英

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?

A quick way is using the Scanner class. 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 */ } . 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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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