Sue said:
Hi, I have a text file of the foll format
date <end line>
some text <end line>
some more text <end line>
date <end line>
some text <end line>
more text<end line>
date
I am using Datainputstream readLine to read line by line -- how can I
tell the program to start reading from one date and stop when the next
date is found and put everything from one date to the next in one line?
Example, I need
date some text some more text <end line>
date some text more text <end line>
and so on... thank you very much for helping.
First, you have to assume that the text will never look like a date. You
also need to specify what a date looks like using the DateFormat system.
Beyond that, the way it works is that you have a date followed by zero or
more lines which are then followed by another date. The lines are
concatenated into a single StringBuffer, but you won't know that you're done
until you receive either the next date or the end of the file. You also
have to figure out what to do if you receive a date followed by another date
(zero lines) or a date at the end of the file. (If line collector is null,
there were no lines since the last date, otherwise it contains the most
recent lines.)
Essentially this algorithm is always ready to add another string onto a line
buffer. If the string can be parsed into a date, the waiting line is
complete and can be processed along with the next date. The line collector
then restarts to collect more lines. Any line that doesn't parse is added
to the end of the collector. The code is for illustrative purposes only and
won't compile.
SimpleDateFormat sdf = new SimpleDateFormat ("MM/DD/YYYY");
BufferedInputReader br = new BufferedInputReader (...);
String line = br.readLine ();
StringBuffer lineCollector = null;
while (line != null) {
try {
Date d = sdf.parse (line);
// You have received a date. This terminates whatever prior
// sequence of lines you were working on and restarts a new one
if (lineCollector != null) {
// Do what you want with the prior sequence of lines
lineCollector = null;
}
// Do what you want with the date
} catch (FormatException ex) {
if (lineCollector == null) {
// this is the first line of the sequence
lineCollector = new StringBuffer ();
}
lineCollector.append (line);
}
line = br.readLine ();
}
// The lineCollector has the last line (if any) here.
Cheers,
Matt Humphrey (e-mail address removed)
http://www.iviz.com/