Fill a ["[]" two-dimensional array "from a text file with elements separated by commas and lines

0

Well as the title says.

I have a .txt with things like:

.

[Without the quotes]

It is a list of 4 elements per row, and 150 rows.

I imagine adding it to an array or arrayList, but I do not know how to read the .txt to go adding each element to each index of the array.

If there is a better method to do it [fill the arrangement] then welcome suggestions. I can also change the source of my data, if a txt is very complicated, or primitive, or there is some better way, go ahead, I chose a txt because I figured it could be easier.

    
asked by José Herrera Avila 13.09.2017 в 07:08
source

1 answer

4

What you have to do is read the file line by line and, on each line, separate by commas.

To read the file line by line you have to do:

public class lee_fichero {
  public static void main(String args[]) {
    String fichero = args[0];
    String[][] arr = new String[150][4];
    int i=0
    try {
      FileReader fr = new FileReader(fichero);
      BufferedReader br = new BufferedReader(fr);

      String linea;
      while((linea = br.readLine()) != null){
          System.out.println(linea);  //Aquí tenemos las líneas por separado
          arr[i++]=linea.split(",");

      }
      fr.close();
    }
    catch(Exception e) {
      System.out.println("Excepcion leyendo fichero "+ fichero + ": " + e);
    }
  }
}

If you would like to do it dynamically (if you do not know the amount of data in the file) you would have to read the file twice, one to count lines and words and another to decompose it or do it with lists (now I would have to think about it little more)

Part of code taken from: link

    
answered by 13.09.2017 / 07:52
source