Parsing a text file delimited with dashes

Wed, Aug 2, 2023 2-minute read

Let’s say you want to parse a text document with variable numbers of lines in each section and which is delimited with dashes:

Gabriel García Márquez
1927 2014
Cien años de soledad
1967
Crónica de una muerte anunciada
1981
---
J. M. Coetzee
1940
Dusklands
1974
Life & Times of Michael K
1983
Disgrace
1999
---
Claude Simon
1913 2005
L'Herbe
1958
Histoire
1967
Triptyque
1973
---
  1. Open a Scanner over the entire books file
  2. While there is still another String in the file
  3. Save the following two lines as authorName and yearsActive (nasty that some are still alive)
  4. Save that Author object
  5. While there is another line in the file:
  6. Put the next line into the bookTitle variable
  7. Check if that line is a --- delimiter and if so, break out of the loop and start at the top (step 2), getting a new author
  8. If not, get the next line as the year (unfortunately saving the year as a string) and create a new Book object with these details and save it to the Author’s catalog.
        try {
            Scanner scan = new Scanner(new File("books.txt"));
            
            while (scan.hasNext()) {
                String authorName = scan.nextLine();
                String yearsAlive = scan.nextLine();

                Author author = new Author(authorName, yearsAlive);
                authors.add(author);

                while (scan.hasNextLine()) {
                    String bookName = scan.nextLine();
                    if (bookName.equals("---")) {
                        break;
                    }

                    String bookYear = scan.nextLine();

                    Book book = new Book(bookName, bookYear, author);
                    author.addBook(book);

                }

            }
        } catch (IOException e) {
            UI.println("File error: " + e);
            e.printStackTrace();
        }