Android reads and writes files in external storage and android reads and writes
This article mainly introduces how to read and write data through external storage in android
SD card path
Sdcard: SD card path before 2.3
Mnt/sdcard: SD card path before 4.3
Storage/sdcard: SD card path after 4.3
Open file explorer
You can see that sdcard is an empty folder, because this folder is a shortcut, pointing to the/storag folder, and then open the storag folder
Read/write SD card
The simplest way to open the SD card
File file = new File ("sdcard/info.txt ");
* Permissions are required for writing SD cards.
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>
Run the program
* Read the SD card. You do not need permissions before 4.0. You can set permissions after 4.0 as needed.
<Uses-permission android: name = "android. permission. READ_EXTERNAL_STORAGE"/>
Obtain the path of the SD card through api
* Use the api to obtain the real path of the SD card. Some mobile phone brands will change the path of the SD card.
Environment. getExternalStorageDirectory ()
* Determine whether the SD card is ready
If (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED ))
The complete code is as follows:
Public void saveAccount (String name, String pass) {// determines the SD card status if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {// get a file object. The path is the real path of the SD card, File file = new File ("sdcard/info.txt "); try {FileOutputStream fos = new FileOutputStream (file); fos. write (name + "#" + pass ). getBytes (); fos. close ();} catch (Exception e) {e. printStackTrace () ;}} else {Toast. makeText (this, "SD card unavailable", 0 ). show () ;}} public void loadAccount () {File file = new File ("sdcard/info.txt"); if (file. exists () {try {FileInputStream FCM = new FileInputStream (file); // convert byte stream to byte stream BufferedReader br = new BufferedReader (new InputStreamReader (FCM )); string text = br. readLine (); String [] s = text. split ("#"); // obtain the user-input account and password EditText et_name = (EditText) findViewById (R. id. et_name); EditText et_pass = (EditText) findViewById (R. id. et_pass); et_name.setText (s [0]); et_pass.setText (s [1]);} catch (Exception e) {e. printStackTrace ();}}}