Reading rows from a TXT to ArrayList

1

I need to read a log recorded in a TXT file that contains geographic coordinates in the following form:

-54.123440,-21.123456
-54.123425,-21.123467
-54.123435,-21.123480
-54.123444,-21.123444
-54.123452,-21.123100

Each line has the longitude and latitude of each coordinate (plot point), separated by a comma (,).

I will use these coordinates to generate a graph where each line is a point, so I need access to the latitude and longitude of each point. I would like to know how to store the latitude and longitude of each point in a ArrayList , and if this is really the best way to do it so I have access to that data to generate the graph later.

I can read the file and print line by line, through the following class:

public class Leitura {

    public void leTXT() {
        Scanner ler = new Scanner(System.in);
        try {
            FileReader arq = new FileReader("c:/dados/log.txt");
            BufferedReader lerArq = new BufferedReader(arq);
            String str = lerArq.readLine();
            while (str != null) {
                System.out.printf("%s\n", str);
                str = lerArq.readLine();
            }
            arq.close();
        } catch (IOException e) {
            System.err.printf("Erro na abertura do arquivo!");
        }

        System.out.println();
    }
}
    
asked by anonymous 18.05.2018 / 21:23

2 answers

4

In your file, each line corresponds to a coordinate and each coordinate has a longitude (between -180 and +180) latitude (between -90 and +90). The content of the file is a coordinate list .

Notice that the central concept we have here is a coordinate. As Java is an object-oriented language, these concepts map to objects that are modeled in classes. Therefore, Coordenada is a class:

public final class Coordenada {
    private final double longitude;
    private final double latitude;

    public Coordenada(double longitude, double latitude) {
        if (longitude < -180.0 || longitude > 180.0) {
            throw new IllegalArgumentException("Longitude inválida.");
        }
        if (latitude < -90.0 || latitude > 90.0) {
            throw new IllegalArgumentException("Latitude inválida.");
        }
        this.longitude = longitude;
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return longitude;
    }

    public static Coordenada parse(String linha) {
        String[] partes = linha.split(",");
        if (partes.length != 2) throw new IllegalArgumentException("Linha malformada.");

        double a, b;
        try {
            a = Double.parseDouble(partes[0]);
            b = Double.parseDouble(partes[1]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Linha malformada.");
        }
        return new Coordenada(a, b);
    }
}

Note this parse(String) method. It is responsible for interpreting a line and converting it into a coordinate.

You can use method Files.readAllLines(Path, Charset) to get all the lines of the file easily.

With this, we can do this:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Leitura {

    public List<Coordenada> lerCoordenadas() throws IOException {
        return lerCoordenadas(Paths.get("c:/dados/log.txt"));
    }

    public List<Coordenada> lerCoordenadas(Path arquivo) throws IOException {
        return Files.readAllLines(arquivo, StandardCharsets.UTF_8)
               .stream()
               .map(Coordenada::parse)
               .collect(Collectors.toList());
    }
}

In this case, you do not have to worry about opening, reading, and closing the file manually because Files.readAllLines already does this. But if you do it manually, remember to use try-with-resources .

    
18.05.2018 / 21:48
0

Without knowing which graphic library you're going to use, here's a generic solution, which uses Map to store the latitude / longitude set.

public HashMap<Double, Double> getCoordenadas() throws IOException{     

    HashMap<Double, Double> retorno = new HashMap<>();

    List<String> linhas = Files.readAllLines(Paths.get("C:\dados\log.txt"));

    for (String linha : linhas) {
        String[] coordenadas = linha.split(",");
        retorno.put(Double.valueOf(coordenadas[0]), Double.valueOf(coordenadas[1]));
    }

    return retorno;
}

Note that I used a different method to read the file, the Files class.

If your project uses Java 8, I recommend using it, because as you can see, it greatly reduces the complexity of the code.

    
18.05.2018 / 21:44