[ACCEPTED]-What is the best way to read a text file two lines at a time in Java?-fileparsing
Accepted answer
Why not just read two lines?
BufferedReader in;
String line;
while ((line = in.readLine() != null) {
processor.doStuffWith(line, in.readLine());
}
This assumes 2 that you can rely on having full 2-line 1 data sets in your input file.
BufferedReader in;
String line1, line2;
while((line1 = in.readLine()) != null
&& (line2 = in.readLine()) != null))
{
processor.doStuffWith(line1, line2);
}
Or you could concatenate them if you wanted.
0
I would refactor code to look somehow like 5 this:
RecordReader recordReader;
Processor processor;
public void processRecords() {
Record record;
while ((record = recordReader.readRecord()) != null) {
processor.processRecord(record);
}
}
Of course in that case you have to 4 somehow inject correct record reader in 3 to this class but that should not be a problem.
One 2 implementation of the RecordReader could 1 look like this:
class BufferedRecordReader implements RecordReader
{
BufferedReader in = null;
BufferedRecordReader(BufferedReader in)
{
this.in = in;
}
public Record readRecord()
{
String line = in.readLine();
if (line == null) {
return null;
}
Record r = new Record(line, in.readLine());
return r;
}
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.