Read two lines of CSV at a time (Java)
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.S开发者_StackOverflow中文版mith,blah,blah
action,4,10
....
Thanks in advance.
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
}
String line = input.nextLine() + input.nextLine();
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();
精彩评论