(1) Directory of files
(2) The 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:paddi ngbottom= "@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/bu Tton1 "android:layout_marginright=" 44DP "android:layout_margintop=" 78DP "android:src=" @drawable/ic_la Uncher "/> <button android:id=" @+id/button1 "android:layout_width=" Wrap_content "Android:lay out_height= "Wrap_content" Android:layout_aligNparentleft= "true" android:layout_below= "@+id/imageview1" android:layout_marginleft= "96DP" Android:la yout_margintop= "106DP" android:text= "button"/></relativelayout>
Fileservice.java is the tool class that operates 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;/** * SDcard exist in context-independent * * @author Piaodangdehun * */public class FileS Ervice {/* * stored in SDcard root directory */public boolean savefiletosdcardroot (String fileName, byte[] data) {Boolean flag = false;/* * First determine the state of the sdcard, whether there is a */string states = Environment.getexternalstoragestate (); FileOutputStream outputstream = null; File rootfile = Environment.getexternalstoragedirectory (); Get sdcard Root Path */* indicates sdcard is mounted on the phone and can read and write */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;} /* * Stored under SDcard Custom directory */public boolean savefiletosdcarddir (String fileName, byte[] data) {Boolean flag = false;/* * First Judge SDC The state of ARD, whether the presence of */string states = Environment.getexternalstoragestate (); FileOutputStream outputstream = null; File rootfile = Environment.getexternalstoragedirectory (); Obtaining the root path of the SDcard * * indicates that sdcard is mounted on the phone and can read and 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, fileName); try {outputstream.write (data, 0, data.length); flag = t Rue;} catch (IOException e) {e.printstacktrace ();}} catch (FileNotFoundException e) {e.printstacktrace ();} finally {if (outputstream! = null) {try {outputstream.close ();} CA TCH (IOException e) {e.printstacktrace ();}}}} return flag;} /* * For reading SDcard data */public string Readcontextfromsdcard (String fileName) {string state = EnviRonment.getexternalstoragestate (); File roofile = Environment.getexternalstoragedirectory (); Get SDcard directory FileInputStream InputStream = null;//stream for data fetching bytearrayoutputstream OutputStream = new Bytearrayoutputstream (); Data to hold for solitude 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 the file to a fixed file * * @param fileName * @param data */public void Savefiletosdcardbysuff (String FileName, byte[] data) {//File File = Environment.getexternalstoragepublicdirectory ("");//directory to save files file File = null 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, fileName); try { Outputstream.write (data, 0, data.length);} catch (IOException e) {e.printstacktrace ();}} catch (FiLenotfoundexception e) {e.printstacktrace ();} finally {if (outputstream! = null) {try {outputstream.close ()} catch (Ioex Ception 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 ()) {exit File.delete ();}} return flag;}}
Httputils.java access to the network
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 () = = () {data = Entityutils.tobytearray (Response.getentity ());}} catch (Clientprotocolexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally { Httpclient.getconnectionmanager (). shutdown ();} return data;}}
Imagecache.java put the file in the cache:
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 (environment.media_mounted)) {try {OutputStream = new FileOutputStream (new 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 (Ioexcept Ion 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_storage_ Sdcard.http.httputils;import Com.example.data_storage_sdcard.img.imagecache;public class MainActivity extends Activity {private Button button;private ImageView imageview;private progressdialog progressdialog;private String Imagename;private final String pathstring = "Http://www.baidu.com/img/bd_logo1.png"; @Overrideprotected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); button = ( Button) This.findviewbyid (r.id.button1), ImageView = (ImageView) This.findviewbyid (r.id.imageview1);p Rogressdialog = New ProgressDialog (This);p rogressdialog.settitle ("Download Hint");p rogressdialog.setmessage ("Load ..."); Button.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {new MyTask (). Execute (pathstring);}});} Class MyTask extends asynctask<string, void, byte[]> {@Overrideprotected void OnPreExecute () {Super.onpreexecute ( );p rogressdialog.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.onprogressupdate (values);} @Overrideprotected void OnPostExecute (byte[] result) {Super.onpostexecute (result); if (result! = null) {Bitmap BM = Bitmap Factory.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 (); fil Eservice.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 include access to the network in the unit press, permissions to operate SDcard, permissions to test
<?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= "/> <instrumentation android" : Name= "Android.test.InstrumentationTestRunner" android:targetpackage= "Com.example.data_storage_sdcard" > < /instrumentation> <!--Add permissions to access SDcard-<uses-permission android:name= "Android.permission.WRITE_EXTERN Al_storage "/> <!--Add permissions to access the network--<uses-permission android:name=" Android.permission.INTERNET "/> & Lt;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> </uses-library> ; </application></manifest>
SDcard storage method and operation SDcard of the data of the Android learning note