在本文中,我們將探討如何在Android 上的檔案中儲存字串Android裝置的內部存儲,隨後檢索它以供您使用app.
首先,您需要將 EditText 視圖中的文字儲存到文件中。操作方法如下:
private void writeToFile(String data, Context context) { try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE)); outputStreamWriter.write(data); outputStreamWriter.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } }
現在,您可以讀取已儲存的檔案並將其內容儲存在變數中以供以後使用:
private String readFromFile(Context context) { String ret = ""; try { InputStream inputStream = context.openFileInput("config.txt"); if ( inputStream != null ) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String receiveString = ""; StringBuilder stringBuilder = new StringBuilder(); while ( (receiveString = bufferedReader.readLine()) != null ) { stringBuilder.append("\n").append(receiveString); } inputStream.close(); ret = stringBuilder.toString(); } } catch (FileNotFoundException e) { Log.e("login activity", "File not found: " + e.toString()); } catch (IOException e) { Log.e("login activity", "Can not read file: " + e.toString()); } return ret; }
實作這些方法後,您可以呼叫writeToFile 將資料儲存到內部儲存並呼叫readFromFile 來檢索資料。
以上是如何在 Android 檔案中讀取和寫入字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!