2016-12-15 1 views
1

Я пытаюсь использовать класс RandomAccessFile для чтения и записи информации из файла .json, который я вытащил из файла URL во внутренний файл приложения для Android, но у меня проблемы. Я убедился, что я положил url.oponConnection(); в AsyncTask, поэтому ему не нужно запускать основное действие, и я проверил, что информация считывается из файла .json. (Я выводил каждую строку на мой логарифм).Почему не RandomAccessFile.seek (0); переместить указатель обратно в начало файла?

Теперь моя проблема в том, что я не могу прочитать созданный мной файл, потому что указатель на RandomAccessFile не перемещается в начало файла даже после того, как я использовал RandomAccessFile.seek(0) Я хотел бы сделать этот файл a .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":"" 
    } 
} 
+2

он выглядит сложнее. writeString создает новый экземпляр RandomAccessFile() каждый раз, когда он вызывается. не должно быть необходимости использовать RandomAccessFile в любом случае. они нужны только при редактировании разделов внутри файла. для текстовых файлов, подобных этому, вы должны уйти с использованием обычных FileInputStreams и FileOutputStreams - и не открывать их повторно для каждой строки. – slipperyseal

+0

Спасибо, я попытаюсь использовать их вместо этого. Я учу себя, как это сделать, и я был так потерян. Я ценю ваше предложение. – Dusk

+0

Итак, я смотрю на веб-сайт ниже, чтобы узнать, как использовать FileInputStreams, и он говорит, что он возвращает байты. Есть ли в любом случае, что я могу прочитать файл и вернуть строку в виде строки? https://developer.android.com/reference/java/io/FileInputStream.html – Dusk

ответ

0

Так я понял, как для чтения/записи данных в виде строки с использованием Scanner и BufferedWriter. Вот отредактированный класс 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(); 
      } 
     } 
    } 
} 
Смежные вопросы