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();
    		}


  • 相关阅读:
    【leetcode】1415. The k-th Lexicographical String of All Happy Strings of Length n
    【leetcode】1413. Minimum Value to Get Positive Step by Step Sum
    【leetcode】1410. HTML Entity Parser
    【leetcode】1409. Queries on a Permutation With Key
    1, 2, and 4 symbols per clock中数据排列
    RGB转换成YCbCr
    RAW转换成RGB
    ROM的一种写法
    IP之ALTIOBUF仿真
    IP之ALTDDIO_in仿真
  • 原文地址:https://www.cnblogs.com/riasky/p/3473388.html
Copyright © 2011-2022 走看看