码迷,mamicode.com
首页 > 移动开发 > 详细

Android---36---读取SD卡内容

时间:2015-05-06 19:45:06      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:android

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" />





Android---36---读取SD卡内容

标签:android

原文地址:http://blog.csdn.net/u013476556/article/details/45539777

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!