android保存文件到SD卡中

想把文件保存到SD卡中,一定要知道SD卡的路径,有人说可以用File explore来查看,这种方法不太好,因为随着android版本的升级,SD卡的路径可能会发生改变。在1.6的时候SD的路径是/sdCard。后续版本都改成了mnt/sdCard。所有还是使用API来获取:

 

Environment.getExternalStorageDirectory()


另外,在保存之前要判断SD卡是否已经安装好,并且可读写:

 

 

//判断SDcard是否存在并且可读写
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
					service.saveToSDCard(filename,filecontent);
					Toast.makeText(getApplicationContext(), R.string.success, 1).show();
				}else{
					Toast.makeText(getApplicationContext(), R.string.sdcarderror, 1).show();
				}


查看完整代码:

 

 

	/**
	 * 保存到SD卡
	 * @param filename
	 * @param filecontent
	 * @throws Exception
	 */
	public void saveToSDCard(String filename, String filecontent)throws Exception{
		File file = new File(Environment.getExternalStorageDirectory(),filename);
		FileOutputStream outStream = new FileOutputStream(file);
		outStream.write(filecontent.getBytes());
		outStream.close();
	}	

 

	@Override
		public void onClick(View v) {
			EditText filenameText = (EditText)findViewById(R.id.filename);
			EditText filecontentText = (EditText)findViewById(R.id.filecontent);
			String filename = filenameText.getText().toString();
			String filecontent = filecontentText.getText().toString();
			FileService service = new FileService(getApplicationContext());
			try {
				//判断SDcard是否存在并且可读写
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
					service.saveToSDCard(filename,filecontent);
					Toast.makeText(getApplicationContext(), R.string.success, 1).show();
				}else{
					Toast.makeText(getApplicationContext(), R.string.sdcarderror, 1).show();
				}
				
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
				e.printStackTrace();
			}
			Toast.makeText(getApplicationContext(), R.string.success, 1).show();
		}


 

 

posted on 2013-12-13 16:29  love so much  阅读(545)  评论(0编辑  收藏  举报

导航