I'm trying to use the RandomAccessFile class to read and write information from a .json
file that I pulled from a URL
to an internal file for an android app, but I'm having some trouble. I've made sure that I put url.oponConnection();
in an AsyncTask
so it doesn't have to run on the main activity, and I have verified that the information is being read from the .json
file. (I have it output each line to my logcat).
Now my problem is that I can't read the file I created, because the pointer for the RandomAccessFile isn't being moved to the start of the file even after I've used RandomAccessFile.seek(0)
I would like to make this file a .txt
file if possible. I know this is a lot of code to read, but I have looked everywhere and I can't figure it out. Any help is appreciated.
AsyncTask
public class AsyncTaskActivity extends Activity {
public static class AsyncInfo extends AsyncTask<Void, Void, String>
{
protected void onPostExecute() {
}
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(Void... params) {
try {
Log.i("AsyncTask", "Loading...");
// Make a URL to the web page
URL url = new URL("http://api.wunderground.com/api/0c0fcc3bf62ab910/conditions/q/IN/Fort_Wayne.json");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
// read each line and write to text file
while ((line = br.readLine()) != null) {
Log.i("AsyncTask", line);
TextEditor.file = new File(MainActivity.path, "siteInfo.txt");
TextEditor.writeString(line);
}
TextEditor.saveAndClose();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("AsyncTask", "DONE");
return "Executed";
}
}
}
TestEditor class here is where I am trying to read and write the file
public class TextEditor {
public static File file;
private static RandomAccessFile in;
private static RandomAccessFile out;
private static String s;
/**
* Opens a file to be used for input (if not already open),
* reads a line from the file, and returns the entire line of data.
*
* @return a line of text from the input file
*/
public static String readString() {
if (in == null) {
try {
in = new RandomAccessFile(file, "rw");//new BufferedReader(new FileReader(file));
in.seek(0);
s = in.readLine();
Log.e("readString", "STRING S: " + s + ".");
return s;
} catch (Exception e) {
System.err.println("Cannot open file for input!");
e.printStackTrace();
}
}
return s;
}
/**
* Opens a file to be used for output (if not already open),
* writes a string to the file and wrties a newline.
*
* @param s The string text to be written. Follwing the string, a newline is added to the file.
*/
public static void writeString(String s) {
try {
out = new RandomAccessFile(file, "rw");
out.seek(0);
out.write(s.getBytes());
}
catch (IOException e) {
e.printStackTrace();
Log.e("writeString", "File Writer Failure");
}
}
/**
* Saves and closes the file (when opened for either input or output).
* <p/>
* Note: If the program terminates before the file is closed,
* no data will be saved or written to the file.
*/
public static void saveAndClose() {
if (in != null) {
try {
in.close();
in = null;
} catch (Exception e) {
System.err.println("Cannot close input file!");
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
out = null;
} catch (Exception e) {
System.err.println("Cannot close output file!");
e.printStackTrace();
}
}
}
This is the .json
file
{
"response": {
"version":"0.1",
"termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
}
, "current_observation": {
"image": {
"url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",
"title":"Weather Underground",
"link":"http://www.wunderground.com"
},
"display_location": {
"full":"Fort Wayne, IN",
"city":"Fort Wayne",
"state":"IN",
"state_name":"Indiana",
"country":"US",
"country_iso3166":"US",
"zip":"46801",
"magic":"1",
"wmo":"99999",
"latitude":"41.13000107",
"longitude":"-85.12999725",
"elevation":"242.9"
},
"observation_location": {
"full":"Ludwig Park, Fort Wayne, Indiana",
"city":"Ludwig Park, Fort Wayne",
"state":"Indiana",
"country":"US",
"country_iso3166":"US",
"latitude":"41.135193",
"longitude":"-85.150581",
"elevation":"774 ft"
},
"estimated": {
},
"station_id":"KINFORTW73",
"observation_time":"Last Updated on December 14, 10:34 PM EST",
"observation_time_rfc822":"Wed, 14 Dec 2016 22:34:42 -0500",
"observation_epoch":"1481772882",
"local_time_rfc822":"Wed, 14 Dec 2016 22:34:50 -0500",
"local_epoch":"1481772890",
"local_tz_short":"EST",
"local_tz_long":"America/New_York",
"local_tz_offset":"-0500",
"weather":"Partly Cloudy",
"temperature_string":"11.3 F (-11.5 C)",
"temp_f":11.3,
"temp_c":-11.5,
"relative_humidity":"44%",
"wind_string":"From the WSW at 4.9 MPH Gusting to 7.4 MPH",
"wind_dir":"WSW",
"wind_degrees":243,
"wind_mph":4.9,
"wind_gust_mph":"7.4",
"wind_kph":7.9,
"wind_gust_kph":"11.9",
"pressure_mb":"1022",
"pressure_in":"30.17",
"pressure_trend":"+",
"dewpoint_string":"-6 F (-21 C)",
"dewpoint_f":-6,
"dewpoint_c":-21,
"heat_index_string":"NA",
"heat_index_f":"NA",
"heat_index_c":"NA",
"windchill_string":"3 F (-16 C)",
"windchill_f":"3",
"windchill_c":"-16",
"feelslike_string":"3 F (-16 C)",
"feelslike_f":"3",
"feelslike_c":"-16",
"visibility_mi":"10.0",
"visibility_km":"16.1",
"solarradiation":"0",
"UV":"0.0","precip_1hr_string":"0.00 in ( 0 mm)",
"precip_1hr_in":"0.00",
"precip_1hr_metric":" 0",
"precip_today_string":"0.00 in (0 mm)",
"precip_today_in":"0.00",
"precip_today_metric":"0",
"icon":"partlycloudy",
"icon_url":"http://icons.wxug.com/i/c/k/nt_partlycloudy.gif",
"forecast_url":"http://www.wunderground.com/US/IN/Fort_Wayne.html",
"history_url":"http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KINFORTW73",
"ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=41.135193,-85.150581",
"nowcast":""
}
}
So I figured out how to read/write the data as a string using a
Scanner
and aBufferedWriter
. Here is the editedTextEditor
class.