简体   繁体   中英

IndexOutOfBoundsException when reading CSV file

Hi i'm trying to read a CSV file which looks like this ->

CSV File

And i'm trying to read it and add it to an array with this code:

ArrayListlistaProductos2 = new ArrayList();

    Scanner inputStream = null;
    inputStream = new Scanner(new File("src/ProductosImportados2.csv"));
    
    while(inputStream.hasNext()) {
        
        String datos = inputStream.next();
        String[] valores = datos.split(",");
        String articuloImportado = valores[0];
        String precioImportado = valores[1];
        String descripcionImportada = valores[2];
        String codigoImportado = valores[3];
        String tallaImportada = valores[4];
        String marcaImportada = valores[5];
        String colorImportado = valores[6];
        
        Producto nuevoProducto = new Producto(articuloImportado, precioImportado, descripcionImportada, codigoImportado, tallaImportada, marcaImportada, colorImportado);
        listaProductos2.add(nuevoProducto);
        System.out.println(listaProductos2);

I already have a Producto class with it's builder set up, and my program is currently working properly, my only issue goes with importing data from an outside source.

When i target the index 0 and 1 of "valores", it prints correctly, but from index 2 and forward it gives the indexOutOfBounds exception, and i'm kinda lost, i don't know why it's out of bounds.

I've done my research, but haven't figured it out sadly, any help is greatly appreciated.

You need to substitute this:

String datos = inputStream.next();

In to this:

String datos = inputStream.nextLine();

I hope help you, say me if it work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM