Reading data from a file with Java

1

Good evening, I have a text file like the image

I need to read this file and grab the data and save it to an object array. For example, I have a SALA object, this object has the following attributes:

number = room || north = north || south = south || lest = east || west = west || up = up || down = down ||

In the first line, for example, it should look like this

Room Room = new Room (1, null, 6, 2, null, null, null);

I was able to read the file with the scanner, it's quiet, but since the file information does not follow a pattern, I do not know how to capture the correct data ....

Any suggestions?

    
asked by anonymous 07.06.2017 / 02:38

2 answers

1

I made an example for you using split to break the spaces of the lines and save in an array and a switch to see if the name in each of the pieces is equivalent to one of values of the switch and, if married, stores in the room variable the value of the next piece, which is the corresponding value. Seeing the code below will help you understand.

I created a simple Java project with a package called lerarquivotxt and 3 files inside.

To start, we create a Room object that will be used to store the values.

Sala.java

package lerarquivotxt;

public class Sala
{
    int numero,norte,sul,leste,oeste,cima,baixo;

    // Construtor de sala vazia
    public Sala Sala()
    {
        return this;
    }

    // Construtor com parâmetros para preenchimento
    public Sala Sala(int room, int north, int south, int east, int west, int up, int down)
    {
        numero = room;
        norte = north;
        sul = south;
        leste = east;
        oeste = west;
        cima = up;
        baixo = down;

        return this;
    }

}

The second constructor of this Sala class will not be used, but you can use it to test by creating the objects by passing the parameters manually if you want.

The next file is an executable that will read the file and create room-type objects and save them to the list.

ReadFileTxt.java

package lerarquivotxt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class LerArquivoTxt
{
    public static void main(String[] args)
    {
        File f = new File("");

        String caminhoarquivo = "src" + f.separatorChar + "lerarquivotxt" + f.separatorChar + "arquivotexto.txt";

        //System.out.println("Caminho absoluto: " + f.getAbsolutePath());
        System.out.println(f.getAbsolutePath() + f.separatorChar + caminhoarquivo);

        // Lista que armazenará as salas
        ArrayList<Sala> salas = new ArrayList<>();

        Sala sala;

        // Lê o arquivo que está no mesmo pacote
        try
        {
            FileReader arq = new FileReader(f.getAbsolutePath() + f.separatorChar + caminhoarquivo);

            BufferedReader lerArq = new BufferedReader(arq);

            String linha = lerArq.readLine(); // lê a primeira linha
            sala = linha2sala(linha); 
            salas.add(sala);            

            // a variável linha será igual a null ao chegar no fim do arquivo
            while (linha != null)
            {
                linha = lerArq.readLine(); // lê da segunda até a última linha


                if(linha!=null)
                {
                    sala = linha2sala(linha); // converte linha em uma sala
                    salas.add(sala); // salva a sala na lista  
                }
            }
        }
        catch (IOException e) 
        {
              System.err.printf("Erro na abertura do arquivo: %s.\n",
                e.getMessage());
        }     


        // for each que exibe a lista de salas para demonstrar que está tudo correto
        for(Sala minhasala : salas)
        {
            System.out.println( 
                                "Sala: "    + minhasala.numero   + " \t " +
                                "Norte: "   + minhasala.norte    + " \t " +
                                "Sul: "     + minhasala.sul      + " \t " +
                                "Leste: "   + minhasala.leste    + " \t " +
                                "Oeste: "   + minhasala.oeste    + " \t " +
                                "Cima: "    + minhasala.cima     + " \t " +
                                "Baixo: "   + minhasala.baixo    
                               );
        }
    }




    static Sala linha2sala(String linha)
    {
        Sala sala = new Sala();

        // quebra os espaços e guarda num array para poder percorrer com um for

        String[] pedacos = linha.split(" ");

        int qtd = pedacos.length;

        // percorre os pedacos q formavam a linha, setando valores da sala
        for(int i=0; i<qtd; i++)
        {
            // se o pedaço é um nome, o próximo pedaço é o valor correspondente 
            switch(pedacos[i])
            {
                case "room":
                    sala.numero=Integer.parseInt(pedacos[i+1]);
                    break;

                case "north":
                    sala.norte=Integer.parseInt(pedacos[i+1]);
                    break;

                case "south":
                    sala.sul=Integer.parseInt(pedacos[i+1]);
                    break;

                case "east":
                    sala.leste=Integer.parseInt(pedacos[i+1]);
                    break;

                case "west":
                    sala.oeste=Integer.parseInt(pedacos[i+1]);
                    break;

                case "up":
                    sala.cima=Integer.parseInt(pedacos[i+1]);
                    break;

                case "down":
                    sala.baixo=Integer.parseInt(pedacos[i+1]);
                    break;     
            }
        }


        return sala;
    }

}

Note: Just putting the file in the same folder and passing its name it was not being found, so I used a getAbsolutePath from an empty file and mounted the path. I do not know if this is the best way to deal with file paths, but solved it with no problem. However I do accept opinions on how this can be improved.

The third file is the list you passed. I took your picture and converted it to text using an OCR Online website, then included \ r \ nto break each line.

archivotext.txt

room 1 south 6 east 2 
room 2 east 3 west 1 
room 3 south 8 east 4 west 2 
room 4 south 7 east 5 west 3 
room 5 south 9 west 4 
room 6 north 1 south 10 west 0 
room 7 north 4 east 9 west 8 
room 8 north 3 south 12 east 7 up 24 
room 9 north 5 south 13 west 7 
room 10 north 6 south 14 east 11 
room 11 east 12 west 10 up 22 
room 12 north 8 south 15 west 11 
room 13 north 9 south 17 
room 14 north 10 south 0 
room 15 north 12 east 16 west 0 up 25 
room 16 east 17 west 15 
room 17 north 13 south 0 west 16 
room 18 north 24 south 25 east 19 west 22 up 28 
room 19 south 26 east 20 west 18 
room 20 east 19 
room 21 east 22 
room 22 north 23 east 18 west 21 down 11 
room 23 south 22 east 24 
room 24 south 18 west 23 down 8 
room 25 north 18 east 26 down 15 
room 26 north 19 west 25 
room 27 east 28 
room 28 north 30 south 31 east 29 west 27 down 18 
room 29 west 28 
room 30 south 28 
room 31 north 28 

If this answer has helped you solve your problem, give it a moral by accepting it as a response and clicking the triangle up to give a +1.

    
07.06.2017 / 07:27
0

Speak, Rafael.

Do you already have text saved in some Java data structure? If you have a stream with the content you can give a look at how to transform into String. If you have a String with the content you can do a search on how to make this a list of strings with one item for each line.

Having the lines you can use regex with the search functions of each property.

You may notice that there is a pattern:

[1]comodo [2]número-do-comodo[n]plano-cartesiano...

Then just save to your object while iterating through the list.

    
07.06.2017 / 03:59