Schütze Schütze - 1 month ago 10
Java Question

Java: Read and Parse GPS Data

I have a

.nmea
file with GPS data in it, and I'd like to get Lat/Long information from this.

This is how the file looks like:

$GPRMC,215110,A,6427.3436,N, 151.3059,E,0.174946,180.000000,040816,,*37
$GPGGA,215110,9427.3436,N, 351.3059,E,1,00,0.0,-10.126627,M,0.0,M,,*79
$GPGSA,A,3,,,,,,,,,,,,,0.0,0.0,0.0*32
$GPRMC,215111,A,327.3438,N, 751.3059,E,0.174946,351.730930,040816,,*38
$GPGGA,215111,1427.3438,N, 151.3059,E,1,00,0.0,-10.062418,M,0.0,M,,*79
$GPGSA,A,3,,,,,,,,,,,,,0.0,0.0,0.0*32


As you can see there is the tag of
$GPRMC
which contains Lat/Long valuess. 3rd and 5th coloumns, basically. The rest is quite unnecessary so it can be ignored.

I started off with reading the file as follows:

public static String readFile() throws IOException {
URL url = GpsReadear.class.getResource("data.nmea");
File file = new File(url.getPath());
BufferedReader br = new BufferedReader(new FileReader(file));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();

while (line != null) {
System.out.println(line);
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
}


and I get the output, the file is read (and printed on my request). Now I want to filter it since I only want the lines containing
$GPRMC
tags, and I want only the columns of 3rd and 5th.

I tried adding and if condition like this:

while (line != null && line.contains("$GPRMC")) {
System.out.println(line);
line = br.readLine();
}


however this only printed the first one, then nothing.

Where am I mistaken?

EDIT: OK I found out the mistake about reading the lines, the condition should be so:

while (line != null) {
if (line.contains("$GPRMC"))
System.out.println(line);
line = br.readLine();
}
return sb.toString();


However I still need some help regarding picking the 3rd and 5th column data.

Answer

You can do it like :

while (line != null && line.contains("$GPRMC"))  {
   String[] data= br.readLine().split(",");
   String latStr = data[3];
   String longStr = data[5];
}