在 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中文网其他相关文章!