Search code examples
javacsvarraylistsplitspace

Java Csv-data String space split error


I am having some trouble with a command.

I have a file of the type csv which looks like this:

Merkmals-Nr.;Interne Teile-Nr.;Bereich;Fertigungsschritt;...

After reading the File in is want to read one Line and then split the line after ";" by using this codeline.

List<String> datenListe = Arrays.asList(data.split(";"));

Then I do a system.println

How the print should look:
Merkmals-Nr.
Interne Teile-Nr.
Bereich
Fertigungsschritt
...

How the print actually looks:
Merkmals-Nr.
Interne

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at java.util.Arrays$ArrayList.get(Arrays.java:2866)
    at CsvEinlesen.main(CsvEinlesen.java:23)

I figured out that the problem is caused by the space in "Interne Teile-Nr." but I don´t know how to solve the problem with the spaces.

This is thecomplete code:

import java.io.*;

import java.util.*;


public class CsvEinlesen {
  public static void main(String[] args) {
    String fileName = "0-201-08-4473.csv";
    File file = new File(fileName);

    try {
      Scanner csvInputStream = new Scanner(file);

      while (csvInputStream.hasNext()) {
        String data = csvInputStream.next();

        List<String> datenListe = Arrays.asList(data.split(";"));

        for (int i = 0; i < 32; i++) {
          System.out.println(datenListe.get(i));
        }
      }

      csvInputStream.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.out.println("CSV-Datei nicht gefunden");
    }
  }
}

Solution

  • Is it really necessary to convert the array to a List<String> if you still iterate through it like a normal array? Also why did you put 32 as a limit? This is not safe - exactly because you will end up getting errors like ArrayIndexOutOfBoundsException.

    My suggestion, for this example, is to just work with the array like this:

        //the rest of your code...
        while (csvInputStream.hasNext()) {
                String data = csvInputStream.next();
    
                String[] wordsInLine = data.split(";");
    
                for (int i = 0; i < wordsInLine.length; i++) {
                  System.out.println(wordsInLine[i]);
                }
              }
       //the rest of your code ...
    

    Give that a try and see if the error goes away.