Reading File in java running line specifies if it exists

Asked

Viewed 102 times

-1

I am reading java file that has the following structure:

nomedapessoa;data de nascimentodependente1+tipodependente2+tipodependenteN+tipo

There may be none, one or several dependents in each line of the file. The problem is that I can’t walk all dependents of a line if there is.

    if(linha.length() > 36) {
            // se linha maior que 36 possui dependentes
            String dependentes = linha.substring(36);
            // variavel dependentes recebe restante da linha com todos os dependentes 
            String tip = "01"+"02"+"03";        
            String[] vetor = dependentes.split (tip);
            //essa vetor serve para separar os dependentes

            String nomedep = "";
            String tipodep = "";
            int tipodec = 0; //variavel só para converter tipo


                for(int i = 0; i < vetor.length; i++) {
                //aqui pega somente o  primeiro dependente de todas as 
              //  pessoas e queria pegar de todos se existir e imprimir
                nomedep = vetor[i].substring(0,20);
                tipodep = vetor[i].substring(20,22);
                tipodec = Integer.parseInt(tipodep);
                System.out.println(nomedep +" "+ tipodec);
                }

        }
  • You can use the String.split(";"); to return a array as each part of the text. So you can check whether this array has the index 2,3,4,5... and then captures them. Or you can use regex to check if there are dependents and then use the String.split(";"); to capture.

  • Now that you’ve edited the question, this code is very strange. if(linha.length() > 36) This does not mean that there are more than 36 dependents, but more than 36 characters. Also you want to use as separator the ";" or "010203"? That one tip has nothing to do with anything. And then, where the numbers 20 and 22 come from?

  • the data of the dependent person reaches 36 characters if there are more dependent . and the dependent name must have 20 characters. and instead of separating by(;) I am separating by type(01),(02)or(03);

  • That sounds like a XY problem.

  • I’m only getting the first dependent on that last one. I wanted to know how to get the rest if it exists knowing that it can only contain 20 characters and one type each dependent

1 answer

1

Use the method split(String) and then remove the name and birth date of the beginning:

String linha = /* ... */;

String[] partes = linha.split(";");
String nome = partes[0];
String strData = partes[1];

List<String> dependentes = Arrays.asList(partes);
dependentes = dependentes.subList(2, dependentes.size());

for (String dependente : dependentes) {
    // ...
}

If that semicolon after the last dependent is always there, use dependentes.size() - 1 instead of just dependentes.size().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.