Assigning lines from a document to a String array

Asked

Viewed 159 times

0

I am trying to assign to a string array certain document lines, the content of the document is this:

3
50
5,80,0
15,5,1
12,30,0

I want, from the third line, each row to be stored in a given Dice of a String array, for example:

Row 3 with data 5,80,0 was assigned to linhasproc[i], where i is greater than 2.

How could that be possible?

Follow the application code:

NOTE: I know it is not possible to carry out the line linhasproc[i]= linha;. But she gets the idea of what I want to do.

package trabalhoso;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;

public class Lerprocessos {

    public static void main(String[] args) {
        Scanner ler = new Scanner(System.in);

        System.out.printf("Informe o nome de arquivo texto:\n");

        //Lê o nome do arquivo que será aberto
        String nome = ler.nextLine();
        System.out.printf("\nConteúdo do arquivo texto:\n");

        try {

            FileReader arq = new FileReader(nome);
            BufferedReader lerArq = new BufferedReader(arq);

            String linha = lerArq.readLine(); // lê a primeira linha
            // a variável "linha" recebe o valor "null" quando o processo
            // de repetição atingir o final do arquivo texto

            //Atribuindo o numero de processos, onde este se encontra na linha 0 do documento
            int numprocesso = Integer.parseInt(linha);

            int numciclo=0; //Variável que guardará o numero total de ciclos 

            int i=0;

            String linhasproc[]; //Vetor de String criado para guardar cada linha 
            //com as diferentes caracteristicas dos processos

            while (linha != null) {

                //Atribuindo o numero de ciclos, onde este se encontra na linha 1 do documento
                if(i==1){numciclo=Integer.parseInt(linha);}

                //lê da segunda até a última linha
                if(i>=2){
                    linhasproc[i]= linha;
                }

                linha=lerArq.readLine();
                i++;
            }

            System.out.println(numprocesso);
            System.out.println(numciclo);

            arq.close();

        } catch (IOException e) {
            System.err.printf("Erro na abertura do arquivo: %s.\n",
              e.getMessage());
        }

        System.out.println();
  }

}

1 answer

0

Follow the solution the way you wanted to implement it. I have separated in a method a way to know what will be the size of your array, but you will have to do some validations to check if a given line contains numbers, if the number of lines is greater than 2 and so on, the way this may be that on several occasions exceptions may occur, the ideal would be to treat them.

public static void main(String[] args) {
    Scanner ler = new Scanner(System.in);

    System.out.printf("Informe o nome de arquivo texto:\n");

    //Lê o nome do arquivo que será aberto
    String nome = ler.nextLine();
    System.out.printf("\nConteúdo do arquivo texto:\n");

    try {

        FileReader arq = new FileReader(nome);
        BufferedReader lerArq = new BufferedReader(arq);

        String linha = lerArq.readLine(); // lê a primeira linha
        // a variável "linha" recebe o valor "null" quando o processo
        // de repetição atingir o final do arquivo texto

        //Pega a quantidade de linhas para ser setado no array linhasproc
        int qtdlinhas = 0; 
        qtdlinhas = verificaQtdLinhas(nome);

        //Atribuindo o numero de processos, onde este se encontra na linha 0 do documento
        int numprocesso = Integer.parseInt(linha);

        int numciclo=0; //Variável que guardará o numero total de ciclos 

        int i=0;

        String linhasproc[] = new String[qtdlinhas-2]; //Vetor de String criado para guardar cada linha 
        //com as diferentes caracteristicas dos processos

        while (linha != null) {

            //Atribuindo o numero de ciclos, onde este se encontra na linha 1 do documento
            if(i==1){numciclo=Integer.parseInt(linha);}

            //lê da segunda até a última linha
            if(i>=2){
                linhasproc[i-2]= linha;
            }

            linha=lerArq.readLine();
            i++;
        }

        System.out.println(numprocesso);
        System.out.println(numciclo);

        arq.close();

    } catch (IOException e) {
        System.err.printf("Erro na abertura do arquivo: %s.\n",
          e.getMessage());
    }

    System.out.println();

}

private static int verificaQtdLinhas(String nome) throws IOException {
    FileReader arq = new FileReader(nome);
    BufferedReader lerArq = new BufferedReader(arq);
    String linha = lerArq.readLine();
    int qtdLinhas = 0;
    while(linha != null){
        qtdLinhas++;
        linha = lerArq.readLine();
    }
    arq.close();
    return qtdLinhas;
}

Browser other questions tagged

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