Reputation: 39
Using java in android studio I am trying to read a .txt file and parse it to obtain some data.
the file: https://www.ndbc.noaa.gov/data/latest_obs/latest_obs.txt
I am using he following code to parse the data:
String[] splited = str.trim().replaceAll(" +", " ").split(" ");
String sDate1= splited[3] + "/" + splited[4] + "/" + splited[5]
+ "/" + splited[6] + "/" + splited[7];
try{
java.util.Date date1 = new
java.text.SimpleDateFormat("yyyy/MM/dd/hh/mm").parse(sDate1);
System.out.println(date1);
}
catch(Exception e){
System.out.println(e.getMessage());
}
String windSpeed = splited[9];
String waveHeight = splited[11];
String airTemperature = splited[17];
String waterTemperature = splited[18];
System.out.println(windSpeed);
System.out.println(waveHeight);
System.out.println(airTemperature);
System.out.println(waterTemperature);
if(windSpeed.toLowerCase().equals("mm")){
// write your code here
}
if(waveHeight.toLowerCase().equals("mm")){
// write your code here
}
if(airTemperature.toLowerCase().equals("mm")){
// write your code here
}
if(waterTemperature.toLowerCase().equals("mm")){
// write your code here
}
The '//write your code here' will just return 'data N/A' since mm refers to missing data.
My problem is I am unsure how to open the file from the url to be read. I would like to open the file every hour, and parse the data below so i can assign it to their buoys in my application.
Upvotes: 3
Views: 1179
Reputation: 8500
Your data file is coming from the Internet, so you'll need to download the file first before parsing it. While it is possible to download and parse the file at the same time, let's keep it simple at first.
To download the file, there are many ways to do this, but you might start with OkHttp or UrlConnection
(see this SO answer for more info). If you want an alternative, check out Retrofit. Retrofit is a wrapper around OkHTTP to make it a little easier to use for experienced developers, but if you're just getting started, I'd recommend sticking with OkHttp for now until you understand what's going on.
Once the file is downloaded or in memory, you'll probably want to use BufferedReader
(as suggested by rileyjsumner) to read and parse one line at a time using the code you posted.
Because you're asking specifically about Android, you'll need to keep a few things in mind:
Upvotes: 1
Reputation: 563
You may want to use BufferedReader
- javadoc
BufferedReader reader = new BufferedReader(new FileReader("url.txt"));
You can then scan through the context of the file.
while(line = reader.readLine() != null) {
// some code
}
This answer has more information on BufferedReader's as well
Upvotes: 0