6

Javaプログラム内で使用できる配列にCSVファイルをインポートしようとしています。CSVファイルは正常にインポートされ、出力はターミナルに表示されますが、エラーがスローされます。

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

最後に。さらに、配列内の要素を呼び出そうとすると、同じエラーが表示されます。私のコードは以下の通りです:

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

4 に答える 4

6

障害のあるパーサーを自分でハッキングするよりも、適切なCSVパーサーを使用する方がはるかに優れています:http://opencsv.sourceforge.net/

CSVは、考えさせられるような単純な形式ではありません(はい、1行に,2つのデータを分離しないを含めることができます)。

于 2011-06-29T21:19:57.930 に答える
2

これが上記の質問に対する答えです

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

}

}

于 2012-09-10T11:43:52.613 に答える
2

すばらしい図書館がたくさんあるときは、車輪を作り直さないことをお勧めします。次のコードスニップを参照として、 uniVocityパーサーを試してください。

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
    // ......
}

ご覧のとおり、csvデータを配列に解析するタスクを完了するのに必要な行は2行だけです。さらに、ライブラリは、優れたパフォーマンスでCSVデータを解析する機能の完全なリストを提供します。

于 2015-05-15T23:03:15.357 に答える
0

ファイル内の1行に常に3つの列があるという仮定は、すべての行に当てはまるわけではありません。forループステートメントを次の行に置き換えて、例外を排除し、それが発生した理由を確認します。

for (int x=0; x<result.length; x++)
于 2011-06-29T21:26:10.640 に答える