0

I have a file like -

--------------
abc
efg
hig
---------------
xyz
pqr
---------------
fdg
gege
ger
ger
---------------

Whats the best way to write java code which parses this file and creates separate List for each of the block of text between dashes. For example -

List<String> List1 = {abc, efg, hig}
List<String> List2 = {xyz, pqr}
List<String> List3 = {fdg, gege, ger, ger}
vivek garg
  • 283
  • 1
  • 2
  • 15

1 Answers1

1

You can use java.nio.file.Files.lines(Path path) to read a file and read each line using Stream<String> to represent single line of an input file. Here is some short example:

public static void main(String[] args) throws IOException {
    final List<List<String>> lines = new CopyOnWriteArrayList<>();

    final String separator = "---------------";

    Files.lines(new File("/tmp/lines.txt").toPath())
            .forEach(line -> {
                if (separator.equals(line)) {
                    lines.add(new ArrayList<>());
                } else {
                    lines.get(lines.size() - 1).add(line);
                }
            });

    // Remove last empty list
    lines.remove(Collections.emptyList());

    lines.forEach(System.out::println);
}

Output

[abc, efg, hig]
[xyz, pqr]
[fdg, gege, ger, ger]
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131