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





郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。