android saves files to SD card

Keywords: Android

Original link: http://www.cnblogs.com/riasky/p/3473388.html

If you want to save a file to an SD card, you must know the path of the SD card. Some people say you can use File explore to view it. This method is not very good, because with the android version upgrade, the path of the SD card may change. At 1.6, the path of SD is / sdCard. Later versions have been changed to mnt/sdCard. All or use API to get:

 

Environment.getExternalStorageDirectory()


In addition, before saving, judge whether the SD card has been installed, and read and write:

 

 

//Determine whether SDcard exists and is readable and writable
				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();
				}


To view the full code:

 

 

	/**
	 * Save to SD card
	 * @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 {
				//Determine whether SDcard exists and is readable and writable
				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();
		}


 

 

Reproduced at: https://www.cnblogs.com/riasky/p/3473388.html

Posted by Johannes80 on Sat, 19 Oct 2019 13:58:58 -0700