Gusse Gusse - 3 years ago 164
Java Question

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:


Interne Teile-Nr.




How the print actually looks:



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

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.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 =;

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

for (int i = 0; i < 32; i++) {

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

Answer Source

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 =;

            String[] wordsInLine = data.split(";");

            for (int i = 0; i < wordsInLine.length; i++) {
   //the rest of your code ...

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download