tags:

views:

175

answers:

3

Is there a way to read two lines of a csv file at a time in Java?

I can read one at a time using Scanner (it has to be done like this):

String line = input.nextLine();
String[] nline = line.split ("[,]");
......

Here is some sample data and a short explanation. I need these read two at a time so I can can go about my other processing.

the first line that starts with "Create" creates a person the second line "action" is the action of the created person

create,Mr. Jones,blah,blah 
action,1,3
create,Mrs.Smith,blah,blah
action,4,10
....

Thanks in advance.

+3  A: 
String line = input.nextLine() + input.nextLine();
Cory Petosky
Thanks Cory. This pointed me in the right direction.
relyt
+3  A: 

Cory's answer is good but for your next part to work

String[] nline = line.split ("[,]");
......

You need to add the comma in there

String line = input.nextLine() + "," + input.nextLine();
Tone
Thanks tone. That worked like a charm!
relyt
This won't work if you have data like: create,"Smith, John",blah - the split would also catch the , after Smith which is really field data.
Jeremy Raymond
@Jeremy You are right but that is a problem with the delimiter and not the solution. If his data does contain those characters even without this he would have a problem. A better delimiter would be a tab '\t'
Tone
Aye - but he may not have control of the source of data, really pure speculation at this point.
Jeremy Raymond
+4  A: 

If you're looking to parse CSV files in Java I'd avoid line split via the string.split() method. You can run into issues if your field contains commas. For Java I'd recommend opencsv to parse the data. Similar to using the scanner you can read it in line by line, or slurp the entire file if it's not too large, and just iterate over the list to items at a time.

CSVReader reader = ...
String[] firstLine; // fields from first line
String[] secondLine; // fields from second line

while ((firstLine = reader.next()) != null && (secondLine = reader.next()) != null) {
   // do something with two lines        
}     

Or

CSVReader reader = ...
List<String[]> allLines = reader.readAll();
// TODO: validate we have an even number of lines

for (int i = 0; i < allLines.size(); i += 2) {
   String[] firstLine = allLines.get(i);
   String[] secondLine = allLines.get(i+1);

   // do something with two lines
}
Jeremy Raymond