mpowell48 mpowell48 - 6 days ago 5
Java Question

Reading a plain text file with multiple flags java

I have a plain text file, format as follows:

-~-http://www.google.com
-@-Google+
-@-About Google
-~-http://www.somewebpage.com
-@-A
Google
Search
-@-How to Google
-~-http://www.mycoolwebpage.com
-@-Google is Awesome!!!


I need to read in the links (denoted by -~-), and place them in a
List<String>
called links. I also need to read in the outputs (denoted by -@-) and place them in a
List<List<String>>
called outputs. I need to read in all of the text up to the next flag (-~-/\t-@-), and I also need to know which flag preceded the text. I've tried
Delimiter
, but I'm not sure I'm able to know which
Delimiter
preceded the
String

Answer

I would avoid using scanner delimiters. Just read each line and process it in code. For each line, first throw away (or ignore) any leading white space. Then if the line starts with a delimiter, wrap up any pending link/output (see below for what that means). Then,

  • if the line starts with -~-, the text from there to the end of the line is the start of a link, so start accumulating link text (in, say a StringBuilder). Also, if you have a non-empty output list, append the list to the list of lists output.
  • if it starts with -@-, it's the start of an output, so start accumulating output text.
  • if it starts with neither delimiter, it's a continuation line, so append the rest of the line to the current link/output accumulator (perhaps after appending a space or newline).

To "wrap up any pending link/output", convert the current contents of the StringBuilder to a String and add to the appropriate list. Also append any non-empty output list to output.

There are a lot of bookkeeping details to attend to here that I haven't addressed, but that's the basic idea.

Comments