在Android 中寫入/讀取字串
簡介
簡介在Android 中,文件處理對於持久性儲存和檢索資料至關重要。一項常見任務是在文件中保存和讀取字串。本文將引導您完成將字串寫入內部文件,然後將該字串讀回字串變數的過程。
寫入檔案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方法將輸入的文字儲存到「config.txt」檔案並將其檢索到「myID」字串變數中,
結論使用本文提供的方法,您可以輕鬆地在Android 中向檔案寫入和讀取字串,從而實現持久化和檢索裝置內部記憶體上的資料。以上是如何在 Android 中向檔案寫入字串和從檔案讀取字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!