在本文中,我们将探讨如何在 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中文网其他相关文章!