Android --- 36 --- read sd card content, android --- 36 --- sd
1. Call Environment. getExternalStorageState () to determine whether the SD card is inserted on the mobile phone and the application has the permission to read and write the SD card.
Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED)
If the returned value is true, the application has the permission to read and write the SD card.
2. Call the getExternalStorageDirectory () method of Environment to obtain the external memory, that is, the Directory of the SD card.
3. Use FileInputStream FileOutputStream FileReader FIleWriter to read and write files in the SD card.
class Utils {public void MyWrite(String data) throws Exception {File sDfile = Environment.getExternalStorageDirectory();File f = new File(sDfile, "demo.txt");FileOutputStream fos = new FileOutputStream(f);fos.write(data.getBytes());fos.flush();fos.close();}public String MyRead() throws Exception {File sdFile = Environment.getExternalStorageDirectory();File f = new File(sdFile, "demo.txt");FileInputStream fis = new FileInputStream(f);StringBuffer sb = new StringBuffer();int len = 0;while ((len = fis.read()) != -1){sb.append((char)len);}return sb.toString();}}public class MainActivity extends Activity {private EditText write;private Button saveButton, readButton;private TextView show;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);show = (TextView) findViewById(R.id.show);write = (EditText) findViewById(R.id.write);saveButton = (Button) findViewById(R.id.save);readButton = (Button) findViewById(R.id.read);final Utils s = new Utils();try {show.setText(s.MyRead());} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();} saveButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubtry {s.MyWrite(write.getText().toString());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}});readButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubtry {show.setText(s.MyRead());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}});}}
To read and write data on the SD card, you need to add permissions:
Permission created and deleted:
<Uses-permission android: name = "android. permission. MOUNT_UNMOUNT_FILESYSTEMS"/>
Write Permission to SD card:
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>