在Android 中從檔案讀取/寫入字串
從檔案讀取和寫入字串是Android 的基本操作發展。本文將示範如何使用作業系統內建的檔案 I/O 方法來完成這些任務。
將字串寫入檔案
儲存文字字串到內部儲存文件,請按照以下步驟操作:
從檔案讀取字串
要從已儲存的檔案擷取字串,請依照下列步驟操作步驟:
範例程式碼
這是一個示例代碼片段,演示了上述內容操作:
寫作:
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; }
以上是如何在 Android 中讀寫文件字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!