Listing continuous List from opencsv
OK.first i realized that readAll() saved the tokenized String in array index from 0 until it sees the newline char(next row of a csv file) and start again from 0.I want the tokenized String saved in a continuous array.
import au.com.bytecode.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
public class ReadTest {
private static String data0 = "U:\\test-csv1.csv";
private static String [] longArray = new String[50];
private static String[] aString;
private static List<String> longStr = new java.util.ArrayList<String>();
private static int arrayCtr = 0;
private static void copyArray(String aTemp){
longStr.add(arrayCtr, aTemp);
System.out.println(arrayCtr);
arrayCtr++;
}
private static void printElements(){
for(int no =15;no<= 25;no++)
System.out.print("\nelNo "+no+" is: "+longStr.get(no));
System.out.println();
}
public static void main(String[] args) throws IOException {
CSVReader reader1 = new CSVReader(new FileReader(data0),';');
List aList;
while ((aList = reader1.readAll())!= null){
int outer= 0;
String aTemp;
String [] longArray = new String[50];
so here i make a loop to copy the tokenized String to be copied into a List called longStr.
for (int counter= 0;counter <aList.size();counter++){
String [] tempStr = (String[]) aList.get(counter);
开发者_Python百科 for (int j = 0; j < tempStr.length; j++){
aTemp = tempStr[j];
copyArray(aTemp);
// System.out.print(tempStr[j]);
// System.out.println();
System.out.print("strNo: " + j+"="+tempStr[j] + " "+"\n");
System.out.print("TEMP="+aTemp+"\n");
}
this is a counter to obtain the num of row.
System.out.println("loop for no. of element:"+(++outer));
System.out.println();
printElements();
}
printElements is a method to list down the elements in longStr.
I am having a problem in listing all the elements in longStr. This is what I have so far, I tried to arrange tokenized String from readAll() into continuous array as in longStr. When I tried to print out the elements after readAll() finished reading the csv file, it continuously print the elements from printElements() ie nonstop. How do I solve this, and where can I put the printElements() other than inside the while
? I always get error like indexoutofbound if I place it somewhere else.
I think
while ((aList = reader1.readAll())!= null){
is an endless loop. try
if((aList = reader1.readAll())!= null){
Why don't you just call reader.readAll()
and then iterate over that List?
List<String[]> records = reader.readAll();
for (String[] record : records) {
//do something with each record
}
精彩评论