Android learning notes-data Sdcard storage method and sdcard operation tool class, androidsdcard

Source: Internet
Author: User

Android learning notes-data Sdcard storage method and sdcard operation tool class, androidsdcard


(1) file directory


(2) Code of each file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <ImageView        android:id="@+id/imageView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_alignRight="@+id/button1"        android:layout_marginRight="44dp"        android:layout_marginTop="78dp"        android:src="@drawable/ic_launcher" />    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_below="@+id/imageView1"        android:layout_marginLeft="96dp"        android:layout_marginTop="106dp"        android:text="Button" /></RelativeLayout>


FileService. java is the tool class used to operate sdcard:

Package com. example. data_storage_sdcard.file; import java. io. byteArrayOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import android. OS. environment;/*** the existence of sdcard is context-independent ** @ author piaodangdehun **/public class FileService {/** the root directory of the sdcard */public boolean saveFileToSdcardRoot (String FileName, byte [] data) {boolean flag = false;/** first, judge whether the sdcard status exists */String state = Environment. getExternalStorageState (); FileOutputStream outputStream = null; File rootFile = Environment. getExternalStorageDirectory (); // get the root path of the sdcard/** indicates that the sdcard is mounted to the mobile phone and can be read and written */if (state. equals (Environment. MEDIA_MOUNTED) {File file = new File (rootFile, fileName); try {outputStream = new FileOutputStream (file); try {OutputStream. write (data, 0, data. length); flag = true;} catch (IOException e) {e. printStackTrace () ;}} catch (FileNotFoundException e) {e. printStackTrace ();} finally {if (outputStream! = Null) {try {outputStream. close ();} catch (IOException e) {e. printStackTrace () ;}}} return flag;}/** custom directory stored in sdcard */public boolean saveFileToSdcardDir (String fileName, byte [] data) {boolean flag = false;/** first, judge whether the sdcard status exists. */String state = Environment. getExternalStorageState (); FileOutputStream outputStream = null; File rootFile = Environment. getExternalStorageDirectory (); // get the root path of the sdcard /** Indicates that the sdcard is mounted to the mobile phone and can read/write */if (state. equals (Environment. MEDIA_MOUNTED) {File file = new File (rootFile. getAbsoluteFile () + "/txt"); if (! File. exists () {file. mkdirs ();} try {outputStream = new FileOutputStream (new File (file, fileName); try {outputStream. write (data, 0, data. length); flag = true;} catch (IOException e) {e. printStackTrace () ;}} catch (FileNotFoundException e) {e. printStackTrace ();} finally {if (outputStream! = Null) {try {outputStream. close ();} catch (IOException e) {e. printStackTrace () ;}}} return flag;}/** data used to read sdcard */public String readContextFromSdcard (String fileName) {String state = Environment. getExternalStorageState (); File rooFile = Environment. getExternalStorageDirectory (); // obtain the sdcard directory FileInputStream inputStream = null; // The stream ByteArrayOutputStream outputStream = new ByteArrayOutputSt Ream (); // if (state. equals (Environment. MEDIA_MOUNTED) {File file = new File (rooFile. getAbsoluteFile () + "/txt/"); // create a txt directory under the sdcard directory File file2 = new File (file, fileName); int len = 0; byte [] data = new byte [1024]; if (file2.exists () {try {inputStream = new FileInputStream (file2); try {while (len = inputStream. read (data ))! =-1) {outputStream. write (data, 0, data. length) ;}} catch (IOException e) {e. printStackTrace ();} return new String (outputStream. toByteArray ();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {if (outputStream! = Null) {try {outputStream. close ();} catch (IOException e) {e. printStackTrace () ;}}} return null ;} /*** save files to a fixed file by category ** @ param fileName * @ param data */public void saveFileToSdcardBySuff (String fileName, byte [] data) {// File file = Environment. getExternalStoragePublicDirectory (""); // save the File directory file = null; if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {/** set Put different files into different categories */if (fileName. endsWith (". mp3 ") {file = Environment. getExternalStoragePublicDirectory (Environment. DIRECTORY_MUSIC);} else if (fileName. endsWith (". jpg ") | fileName. endsWith (". png ") | fileName. endsWith (". gif ") {file = Environment. getExternalStoragePublicDirectory (Environment. DIRECTORY_PICTURES);} else if (fileName. endsWith (". mp4 ") | fileName. endsWith (". avi ") | fileName. endsWith (". 3gp ") {file = Environment. getExternalStoragePublicDirectory (Environment. DIRECTORY_MOVIES);} else {file = Environment. getExternalStoragePublicDirectory (Environment. DIRECTORY_DOWNLOADS);} FileOutputStream outputStream = null; try {outputStream = new FileOutputStream (new File (file, fileName); try {outputStream. write (data, 0, data. length);} catch (IOException e) {e. printStackTrace () ;}} catch (FileNotFo UndException e) {e. printStackTrace ();} finally {if (outputStream! = Null) {try {outputStream. close ();} catch (IOException e) {e. printStackTrace () ;}}}}/** delete a File */public boolean deleteFileFromSdcard (String folder, String fileName) {boolean flag = false; file File = Environment. getExternalStorageDirectory (); if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {File exitFile = new File (file. getAbsoluteFile () + "/" + folder); if (exitFile. exists () {exitFile. delete () ;}} return flag ;}}

HttpUtils. java

package com.example.data_storage_sdcard.http;import java.io.IOException;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;public class HttpUtils {/* *  */public static byte[] getImage(String path) {byte[] data = null;HttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(path);try {HttpResponse response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() == 200) {data = EntityUtils.toByteArray(response.getEntity());}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {httpClient.getConnectionManager().shutdown();}return data;}}

ImageCache. java:

Package com. example. data_storage_sdcard.img; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import android. OS. environment; public class ImageCache {public static String saveImageCache (String fileName, byte [] data) {File file = Environment. getExternalStorageDirectory (); // root directory FileOutputStream outputStream = null; if (Environment. getExternalStorageState (). equals (Environme Nt. MEDIA_MOUNTED) {try {outputStream = new FileOutputStream (new File (file, fileName); outputStream. write (data, 0, data. length); return file. getAbsolutePath () + "/" + fileName;} catch (Exception e) {e. printStackTrace ();} finally {if (outputStream! = Null) {try {outputStream. close () ;}catch (IOException e) {e. printStackTrace () ;}}} return null ;}}

MainActivity. java

Package com. example. data_storage_sdcard; import android. app. activity; import android. app. progressDialog; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. asyncTask; import android. OS. bundle; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. imageView; import com. example. data_s Torage_sdcard.http.HttpUtils; import com. example. data_storage_sdcard.img.ImageCache; public class MainActivity extends Activity {private Button button; private ImageView imageView; private ProgressDialog ssprogre; private String imageName; private final String pathString = "http://www.baidu.com/img/bd_logo1.png "; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInsta NceState); setContentView (R. layout. activity_main); button = (Button) this. findViewById (R. id. button1); imageView = (ImageView) this. findViewById (R. id. imageView1); progressDialog = new ProgressDialog (this); progressDialog. setTitle ("Download prompt"); progressDialog. setMessage ("load... "); button. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {new mytask(cmd.exe cute (pathString) ;}});} class MyTask extends AsyncTask <String, Void, byte [] >{@ Overrideprotected void onPreExecute () {super. onPreExecute (); progressDialog. show () ;}@ Overrideprotected byte [] doInBackground (String... params) {String name = params [0]; imageName = name. substring (name. lastIndexOf ("/") + 1, name. length (); return HttpUtils. getImage (params [0]);} @ Overrideprotected void onProgressUpdate (Void... values) {super. onProgressUpd Ate (values) ;}@ Overrideprotected void onPostExecute (byte [] result) {super. onPostExecute (result); if (result! = Null) {Bitmap bm = BitmapFactory. decodeByteArray (result, 0, result. length); imageView. setImageBitmap (bm); ImageCache. saveImageCache ("", result);} else {imageView. setImageResource (R. drawable. ic_launcher);} progressDialog. dismiss () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}

Test class:

package com.example.data_storage_sdcard;import java.io.FileWriter;import com.example.data_storage_sdcard.file.FileService;import android.nfc.Tag;import android.test.AndroidTestCase;import android.util.Log;public class MyTest extends AndroidTestCase {public void saveFileToSdcardTest() {FileService fileService = new FileService();fileService.saveFileToSdcardRoot("aa.txt","jkhdsfjkhdskjfhdsjf".getBytes());}public void saveFileToSdcardDir() {FileService fileService = new FileService();fileService.saveFileToSdcardRoot("aa.txt","jkhdsfjkhdskjfhdsjf".getBytes());}public void readContextFromSdcardTest() {FileService fileService = new FileService();String msg = fileService.readContextFromSdcard("aa.txt");System.err.println("-->" + msg);}public void saveFileToSdcardBySuffTest() {FileService fileService = new FileService();fileService.saveFileToSdcardBySuff("aa.avi","asdfkajsgdhagsdfhdgsf".getBytes());}public void delFile() {FileService fileService = new FileService();boolean flag = fileService.deleteFileFromSdcard("txt", "aa.txt");}}

You need to add the network access permission, sdcard operation permission, and test permission to the requesting organization.

<? Xml version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "com. example. data_storage_sdcard "android: versionCode =" 1 "android: versionName =" 1.0 "> <uses-sdk android: minSdkVersion =" 8 "android: targetSdkVersion = "18"/> <instrumentation android: name = "android. test. instrumentationTestRunner "android: targetPackage =" com. example. data_storage_sdcard "> </instrumentation> <! -- Add the permission to access sdcard --> <uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/> <! -- Add Network Access Permissions --> <uses-permission android: name = "android. permission. INTERNET "/> <application android: allowBackup =" true "android: icon =" @ drawable/ic_launcher "android: label =" @ string/app_name "android: theme = "@ style/AppTheme"> <uses-library android: name = "android. test. runner "/> <activity android: name =" com. example. data_storage_sdcard.MainActivity "android: label =" @ string/app_name "> <intent-filter> <action android: name =" android. intent. action. MAIN "/> <category android: name =" android. intent. category. LAUNCHER "/> </intent-filter> </activity> <uses-library> </application> </manifest>




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.