【问题标题】:Why isn't RandomAccessFile.seek(0); moving the pointer back to the start of the file?为什么不是 RandomAccessFile.seek(0);将指针移回文件的开头?
【发布时间】:2016-12-15 03:36:18
【问题描述】:

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

现在我的问题是我无法读取我创建的文件,因为即使在我使用 RandomAccessFile.seek(0) 之后,RandomAccessFile 的指针也没有移动到文件的开头我想做这个如果可能,请归档 .txt 文件。我知道这是要阅读的大量代码,但是我到处查看,但无法弄清楚。任何帮助表示赞赏。

异步任务

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

【问题讨论】:

  • 它看起来过于复杂。每次调用 writeString 都会构造一个新的 RandomAccessFile() 实例。无论如何都不需要使用 RandomAccessFile 。仅当您在文件中编辑部分时才需要它们。对于像这样的文本文件,您应该能够使用普通的 FileInputStreams 和 FileOutputStreams - 并且不要为每一行重新打开它们
  • 谢谢,我会尝试改用这些。我正在教自己如何做到这一点,我已经迷失了。感谢您的建议。
  • 所以我正在查看下面的网站以了解如何使用 FileInputStreams,它说它返回字节。无论如何我可以读取文件并将该行作为字符串返回吗? developer.android.com/reference/java/io/FileInputStream.html
  • 你应该真正使用 JSON 库而不是滚动你自己的解析代码,这会比你想象的更频繁地失败。 android 有内置的 JSON 处理类你可以使用,不要浪费时间自己解析任意对象图:developer.android.com/reference/org/json/JSONObject.html。这也不需要RandomAccessFile,特别是如果通过URL下载流。您必须先缓冲所有内容,因为JSONObject 想要一个字符串作为输入。
  • @dusk 用 InputStreamReader 包装它 - 这有一个 readLine 方法。 stackoverflow.com/questions/7413830/java-read-line-from-file

标签: java android randomaccessfile


【解决方案1】:

所以我想出了如何使用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();
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2015-11-28
    • 2012-02-22
    • 2019-12-09
    相关资源
    最近更新 更多