Parsing Data from CSV to Array in Java
I'm trying to import a CSV file into an array that I can use within a Java program. Th开发者_JAVA技巧e CSV file has successfully imported itself and the output appears on Terminal but it throws the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at CompareCSV.main(CompareCSV.java:19)
at the end. In addition, when I try to call up elements in the array, it also shows the same error. My code is below:
import java.io.*;
import java.util.*;
public class CompareCSV {
public static void main(String[] args) {
String fileName = "sampledata1.csv";
try {
BufferedReader br = new BufferedReader( new FileReader(fileName));
String strLine = null;
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while((fileName = br.readLine()) != null) {
lineNumber++;
String[] result = fileName.split(",");
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are much better off using a proper CSV parser than hacking a faulty one up yourself: http://opencsv.sourceforge.net/
CSV is not the simple format one might be let to think (yes, a line can contain a ,
that does not separate two pieces of data).
This is the answer for above Question
public class Readline {
/**
* @param args
*/
public static void main(String[] args) {
String fileName = "C:/Users/karthikrao/Desktop/cvsFile.csv";
ArrayList<Integer> margins = new ArrayList<Integer>();
BufferedReader br;
String line, token;
int i;
try {
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ",\"");
i = 0;
while (st.hasMoreTokens()) {
token = st.nextToken();
if (margins.size() <= i) {
margins.add((Integer) token.length());
} else {
margins.set(
i,
Math.max(margins.get(i),
(Integer) token.length()));
}
i++;
}
}
br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ",\"");
i = 0;
while (st.hasMoreTokens()) {
token = st.nextToken();
System.out.print(token);
for (int j = 0; j < margins.get(i) - token.length(); j++) {
System.out.print(" ");
}
System.out.print("|");
i++;
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I suggest you not re-inventing wheel when there are so many great libraries out there. Try the uniVocity-parsers with the following code snippt as reference:
public static void main(String[] args) throws FileNotFoundException {
/**
* ---------------------------------------
* Read CSV rows into 2-dimensional array
* ---------------------------------------
*/
// 1st, creates a CSV parser with the configs
CsvParser parser = new CsvParser(new CsvParserSettings());
// 2nd, parses all rows from the CSV file into a 2-dimensional array
List<String[]> resolvedData = parser.parseAll(new FileReader("/examples/example.csv"));
// 3rd, process the 2-dimensional array with business logic
// ......
}
As you can see, only 2 lines required to finish the task of parsing csv data into array. Additionally, the library provides full list of features in parsing CSV data with excellent performance.
Looks like your assumption, that a line in the file always has three columns isn't true for all lines. Replace the for loop statement with the following line to eliminate the exception and see, why it happend:
for (int x=0; x<result.length; x++)
精彩评论