3

.csv ファイルを読み取って各列を配列に保存しようとしているときに、例外の問題が発生しました。長いプログラムに見えるかもしれませんが、そうではありません。私はちょうど15の異なる配列を持っています。

これは例外「Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2」の行です。

部門[i] = dataArray[2];

私にできることはありますか?

      BufferedReader CSVFile = 
            new BufferedReader(new FileReader("Sub-Companies.csv"));

      String dataRow = CSVFile.readLine();
      // Read the number of the lines in .csv file 
      // i = row of the .csv file
      int i = 0; 
      while (dataRow != null){
          i++;
          dataRow = CSVFile.readLine();

        }
      System.out.println(i);
      // Close the file once all data has been read.
      CSVFile.close();

      // End the printout with a blank line.
      System.out.println();

      // Save into arrays
      customer_id = new String[i];
      company_name = new String[i];
      department = new String[i];
      employer = new String[i];
      country = new String[i];
      zipcode = new String[i];
      address = new String[i];
      city = new String[i];
      smth1 = new String[i];
      smth2 = new String[i];
      phone_no1 = new String[i];
      phone_no2 = new String[i];
      email = new String[i];
      website = new String[i];
      customer_no = new String[i];

      // Read first line.
      // The while checks to see if the data is null. If 
      // it is, we've hit the end of the file. If not, 
      // process the data.
      int j;
      int counter;
      i = 0;

      // Read the file again to save the data into arrays
      BufferedReader CSV = 
            new BufferedReader(new FileReader("Sub-Companies.csv"));

      String data = CSV.readLine();

      while (data != null){
          String[] dataArray = data.split(";");
          for (String item:dataArray) {
            customer_id[i] = dataArray[0];
            company_name[i] = dataArray[1];
            department[i] = dataArray[2];
            employer[i] = dataArray[3];
            country[i] = dataArray[4];
            zipcode[i] = dataArray[5];
            address[i] = dataArray[6];
            city[i] = dataArray[7];
            smth1[i] = dataArray[8];
            smth2[i] = dataArray[9];
            phone_no1[i] = dataArray[10];
            phone_no2[i] = dataArray[11];
            email[i] = dataArray[12];
            website[i] = dataArray[13];
            customer_no[i] = dataArray[14];
            }


          //System.out.print(address[i] + "\n"); 
          data = CSV.readLine(); // Read next line of data.
          i++;
      }

前もって感謝します!

一部のデータは "E3B3C5EB-B101-4C43-8E0C-ADFE76FC87FE;"Var Welk" Inh. Kar;NULL;NULL;DE;16278;Rotr 3;Angermünde;NULL;NULL;03331/354348-0;0343331/364548-15 です。 ;info@aalls.com;http://www.adss.com;ipo241」ですが、異なる場合があります (小さいまたは大きい)。

4

7 に答える 7

5

これでうまくいくはずです。基本的には、csv ファイルのマトリックス表現を作成します。

LinkedList<String[]> rows = new LinkedList<String[]>();
String dataRow = CSVFile.readLine();
// Read the number of the lines in .csv file 
// i = row of the .csv file
int i = 0; 
while ((datarow = CSVFile.readLine()) != null){
    i++;
    rows.addLast(dataRow.split(","));
}

String[][] csvMatrix = rows.toArray(new String[rows.size()][]);

csvMatrix[行][列]で...

列にアクセスするときは、次のようにして、アクセスしようとしている列番号が範囲内にあることをアサートします。

if(col < csvMatrix[row].length)
于 2012-11-17T19:02:13.307 に答える
2

使用するのが最善でArraList<String>あり、必要に応じてconvert as Array

問題は、配列サイズを作成するために行数をカウントしていないが、split( ";")に基づいてデータを追加しているため、配列の長さとsplit( ";")から配列に追加できる値に不一致があることです。

于 2012-11-17T18:26:04.540 に答える
2

コードにはいくつかの問題があります。例外は、行の 1 つに十分な「;」が含まれていないという事実によって発生します。分離された値。

あなたのコードの奇妙な点は、次のビットです。

  for (String item:dataArray) {
    customer_id[i] = dataArray[0];

これは単純に、同じ割り当てを 15 回繰り返すことを意味します (for (String item: ...) を削除するだけです)。

私があなたなら、次のようにします。

クラスを作成します。このようなもの:

public class Customer {
    private String customerId;
    private String companyName;

    // ...
    public static Customer create(final String... args) {
        if (args.length != 15) {
            return null; // or throw an exception
        }
        final Customer rv = new Customer();
        rv.setCustomerId(args[0]);
        rv.setCompanyName(args[1]);
        // ...
        return rv;
    }

    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(final String customerId) {
        this.customerId = customerId;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(final String companyName) {
        this.companyName = companyName;
    }
}

コレクションを使用します(上記の投稿で提案されているように):

    BufferedReader csv = new BufferedReader(new FileReader("Sub-Companies.csv"));
    List<Customer> customers = new LinkedList<Customer>();

    String data;
    while ((data = csv.readLine()) != null){
        Customer customer = Customer.create(data.split(";"));
        if (customer != null) {
            customers.add(customer);
        }
    }

コレクションではなく配列が必要な場合は、次のことができます。

Customer[] arr = customers.toArray(new Customer[customers.size()]);

ライブラリを使用してファイルを読み取ります...たとえば、http://opencsv.sourceforge.net/を試すことができます。

于 2012-11-17T18:52:56.860 に答える
1
department[i] = dataArray[2];  

例外は、dataArrayにそれほど多くの要素 (つまり 3) がないことを意味します。
CSV ファイルを解析したい場合は、欠落している要素に対してプレースホルダーが必要であることを指定することで、作業を楽にすることができます。
つまり、次のようなレコードを作成できます。

a;b;c;d;e;f;g;h;j
各文字は列の値を表します、要素が欠落している場合、形式は次のようにする必要
a;;;;;f;g;h;jあります。 a;f;g;h;j

これは珍しい予想ではありませんが、CSV ファイルの標準であり、コードを大幅に簡素化し、行に常に予想される列があるため、配列インデックスの例外を回避します。

于 2012-11-17T18:53:12.320 に答える
0

(Maven の代わりに) Gradle を使用してパラメータ化された JUnit テストにデータをロードする場合の方法は次のとおりです。

// import au.com.bytecode.opencsv.CSVReader;
@Parameters(name = "{0}: {1}: {2}")
public static Iterable<String[]> loadTestsFromFile2() {
    String separator = System.getProperty("file.separator");
    File tFile = loadGradleResource( System.getProperty("user.dir") + 
        separator +  "build" + separator + "resources" + separator +  "test" + 
            separator + "testdata2.csv" );
    List<String[]> rows = null;
    if ( tFile.exists() ) {
        CSVReader reader = null;
        try {
            reader = new CSVReader( new FileReader( tFile ), ',' );
            rows = reader.readAll();
        } catch (FileNotFoundException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }   
    }
    staticlogger.info("Finished loadTestsFromFile2()");
    return rows;
} 
于 2013-03-13T22:14:17.523 に答える