Search code examples
javabufferedreaderreadfile

How to read first two words and last 2 words from each comma seperated line?


I have a .txt file with following content:

NO,6549,Kristiansund,N,Møre,og,Romsdal,08,Kristiansund,1505,63.1101,7.7552
NO,6364,Vistdal,Møre,og,Romsdal,08,Molde,1506,62.7107,7.9319
NO,6365,Vistdal,Møre,og,Romsdal,08,Molde,1506,62.7107,7.9319
NO,6401,Molde,Møre,og,Romsdal,08,Molde,1506,62.7371,7.0068,4
NO,6402,Molde,Møre,og,Romsdal,08,Molde,1506,62.7371,7.0068,4
NO,6403,Molde,Møre,og,Romsdal,08,Molde,1506,62.7371,7.0068,4
NO,8502,Narvik,Nordland,09,Narvik,1806,68.4271,17.4349,4
NO,8503,Narvik,Nordland,09,Narvik,1806,68.4271,17.4349,4
NO,8504,Narvik,Nordland,09,Narvik,1806,68.4271,17.4349,4

I want to pick up the first two words from the beginning of each lines and then i also want to pick up the two last words in each lines.

What i want from the first two words is: NO and all the numbers started with 6, 6549 etc and 8, 8502 etc.

But from the end of line i actually want the Latitude and Longitude, but for some lines there is 4 at the end of line. I dont want them. Any idea how I can do this? I want to create objects so i have this java object class:

public class GeoData {
    private String landskode;
    private String postnummer;
    private String latitude;
    private String longitude;
}

Following code I have until so far is:

try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()))) {

        // TXT file delimiter
        String DELIMITER = ",";

        // read the file line by line
        String line;
        while ((line = br.readLine()) != null) {

            // convert line into columns
            String[] columns = line.split(DELIMITER);

            // print all columns
            System.out.println("GeoData["+ String.join(", ", columns) +"]");
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    }

Solution

  • The first two should just be columns[0] and columns[1]. Then, to check whether the last field is a plain "4" you can use columns[columns.length - 1].equals("4"). Depending on whether this is true or false, the lat/long are columns[columns.length - 3] and columns[columns.length - 2] or columns[columns.length - 1] and columns[columns.length - 2].