Parsing data from CSV to array in Java

I'm trying to import CSV files into arrays that can be used in Java programs The CSV file was successfully imported into itself, and the output is displayed on the terminal, but it will raise an error:

Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 1 
at CompareCSV.main(CompareCSV.java:19)

At the end In addition, it displays the same error when I try to call the elements in the array My code is as follows:

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();
        }
    }   
}

Solution

Using the correct CSV parser is much better than cracking the wrong solution: http://opencsv.sourceforge.net/

CSV is not a simple format that people might think of (yes, a row can contain one without separating two data)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>