How to know the number of strings in a String []?

0

Hi, I have the following problem, I am creating a class so that the file management is more user-friendly for an app that I am creating.

The issue is that when trying to create a custom method to read and tabulate the data of a txt in a String[] I need to know some function that tells me how many are stored before null .

Previously in an earlier version of the class I am creating I used this form:

String[][] leido = new String [2][9999];
String lineaActual = "";

try
{
    FileReader f = new FileReader(txt);
    BufferedReader buffer = new BufferedReader(f);

    for (int i = 0; lineaActual != null ; i++)
    {
        try {lineaActual = buffer.readLine();}
        catch (IOException e) {System.out.println(e.getMessage());}

        leido[0][i] = lineaActual;
        leido[1][0] = Integer.toString(i); //Aqui almacenaba el limite de los String

    }
}
catch (FileNotFoundException e) {System.out.println(e.getMessage());}

return leido;

Excuse my terrible newbie code little by little I try to clean up with the new version I'm doing but I need to know some function that helps me with the account so I do not have to use a String[][] but a String[] .

    
asked by Samu 15.11.2018 в 19:28
source

1 answer

0
String[] leido = new String [10000]; 
String lineaActual = "";
try
{
   FileReader f = new FileReader(txt);
   BufferedReader buffer = new BufferedReader(f);
   int contador = 0; // Inicializa contador
   while (lineaActual != null) // Cuenta hasta que encuentra Null
   {
       try 
       {
          lineaActual = buffer.readLine();
          leido[contador] = lineaActual; // Uso contador de indice, en vez de crear una variable mas, lo cual tambien se podria hacer, pero es mas "eficiente".
          contador++; // Aumenta el contador solo si no se arrojo excepcion, es decir si se leyo algo.
       }catch (IOException e)
       {
          System.out.println(e.getMessage());
       }
   }
}catch (FileNotFoundException e)
{
   System.out.println(e.getMessage());
}
return leido;

I hope this is what you are asking, this means confusing the subject of your code in the read part [1] [0] = ... and the readed variable that you use in the return is not known to be, You could include the complete code including the signature of the method You can also use ArrayList that simplifies you to keep a counter like I did in my case, that actually using the Array.length method gives you the length of that arrangement: read.length

    
answered by 15.11.2018 в 19:44