当前位置: 代码迷 >> Android >> Android-36-读取SD卡内容
  详细解决方案

Android-36-读取SD卡内容

热度:8   发布时间:2016-04-28 01:07:12.0
Android---36---读取SD卡内容
1.调用Environment.getExternalStorageState()判断手机上是否插入了SD卡,并且应用程序具有读写SD卡的权限。
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)


返回值为true代表该应用程序具有读写SD卡的权限。


2.调用Environment的getExternalStorageDirectory()方法来获取外部存储器,也就是SD卡的目录。

3.使用FileInputStream FileOutputStream FileReader  FIleWriter 读写SD卡里的文件。






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;	@Override	protected 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 block			e1.printStackTrace();		} 		saveButton.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View v) {				// TODO Auto-generated method stub				try {					s.MyWrite(write.getText().toString());				} catch (Exception e) {					// TODO Auto-generated catch block					e.printStackTrace();				}			}		});		readButton.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View v) {				// TODO Auto-generated method stub				try {					show.setText(s.MyRead());				} catch (Exception e) {					// TODO Auto-generated catch block					e.printStackTrace();				}			}		});	}}





为了读写SD卡上的数据,需要添加权限:


创建于删除的权限:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>


向SD卡中写入的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />





  相关解决方案