zoukankan      html  css  js  c++  java
  • 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();
    		}


  • 相关阅读:
    CSU1018: Avatar
    ZOJ
    HDU—4463 Outlets 最小生成树
    查询文件中值所在的路径
    mysql语句查询时间检测
    phpmyadmin修改root密码
    检测Linux glibc幽灵漏洞和修补漏洞
    监控宝安装手册
    ubuntu安装环境软件全文档
    ubuntu mysql主从库的搭建
  • 原文地址:https://www.cnblogs.com/riasky/p/3473388.html
Copyright © 2011-2022 走看看