Reading data from a Java file

Asked

Viewed 1,511 times

1

Good evening, I have a text file like the image

Print do arquivo de texto

I need to read this file and take the data and store it in an object array. For example, I have a ROOM object, this object has the following attributes:

number = room || north = North || south = South || lest = East || west = West || up = up || bass = down ||

In the first line for example it should look like this

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

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

any suggestions?

2 answers

3


I made an example for you using split to break the line spaces and save to an array and an switch to check if the name on each of the pieces equals one of the values of the switch and, if married, save in the variable room the value of the next piece, which is the corresponding value. Seeing the code below you will understand better.

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

To start we create a Room object that will serve to store the values.

Java room.

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 class Room will not be used, but you can use it to test creating the objects by manually passing the parameters if you want.

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

Lerarquivotxt.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 don’t know if this is the best way to handle the file paths, but solved without problem. However I accept opinions on how this can be improved.

The third file is the list you passed. I took your image and converted it into text using an online OCR site, then included r n to break each line.

arquivotexto.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 to solve your problem, give a moral accept it as an answer and click the triangle up to give also a +1.

  • That’s right, I’m finishing doing using this logic, I’m just reading the files with the scanner

1

Fala, Rafael.

Do you already have the text saved in some Java data structure? If you have a stream with the content you can search how to turn into String. If you have a string with the content you can give a search on how to turn it into a list of strings with an 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...

Where 1 will be the room, 2 the room number and n will be all that comes after, in this case a group formed by coordenada posição.

Then just store in your object while iterating through the list.

Browser other questions tagged

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