为什么不是RandomAccessFile.seek(0);将指针移回文件的开头?

时间:2016-12-15 03:36:18

标签: java android randomaccessfile

我正在尝试使用RandomAccessFile类从.json文件中读取和写入信息,该文件是从URL提取到Android应用程序的内部文件,但我有一些麻烦。我已确保将url.oponConnection();放入AsyncTask,因此无需在主要活动上运行,并且我已验证正在从.json读取信息文件。 (我把它输出到我的logcat)。

现在我的问题是我无法读取我创建的文件,因为即使在我使用RandomAccessFile.seek(0)之后,RandomAccessFile的指针也没有移动到文件的开头我希望如果可能,将此文件设为.txt文件。我知道这是很多要阅读的代码,但我到处寻找,我无法弄明白。任何帮助表示赞赏。

的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类是我尝试读取和写入文件的地方

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();
            }
        }
    }

这是.json文件

{
  "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":""
    }
}

1 个答案:

答案 0 :(得分:0)

所以我想出了如何使用ScannerBufferedWriter将数据读/写为字符串。这是经过编辑的TextEditor课程。

public class TextEditor {


    public static File file;
    private static Scanner in;
    private static BufferedWriter out;

    /**
     * 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 Scanner(file);
            } catch (Exception e) {
                System.err.println("Cannot open file for input!");
                e.printStackTrace();
            }
        }
        try {
            if (in.hasNext()) {
                String s = in.nextLine();
                return s;
            } else {
                return null;
            }
        } catch (Exception e) {
            System.err.println("Cannot read  file!");
            e.printStackTrace();
        }
        return null;
    }


    /**
     * Opens a file to be used for output (if not already open),
     * writes a string to the file and writes a newline.
     *
     * @param s The string text to be written. Following the string, a newline is added to the file.
     */

    public static void writeString(String s) {
        if (out == null) {
            try {
                out = new BufferedWriter(new FileWriter(file));
            }
            catch (Exception e) {
                System.err.println("Cannot create file for output!");
                e.printStackTrace();
            }
        }

        try {
            out.write(s);
            out.newLine();
        }
        catch (Exception e) {
            System.err.println("Cannot write file!");
            e.printStackTrace();
        }

    }
    /**
     * 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();
            }
        }
    }
}