Android transfers files through contentprovider

Source: Internet
Author: User

We know that data interaction between two Android applications requires contentprovider, which is usually a database operation.
Today, the project needs to use the contentprovider of Android to interact with files on the normal SD card, so I wrote this small example:
Androidmanifest. xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.h3c.test"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="15" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:label="@string/app_name"            android:name=".NotepadTestActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <provider android:name=".TestContentProvider" android:authorities="com.h3c.test" />    </application></manifest>

Testcontentprovider. Java

Package COM. h3C. test; import Java. io. file; import Java. io. filenotfoundexception; import Java. io. ioexception; import Java. util. arraylist; import android. content. contentprovider; import android. content. contentprovideroperation; import android. content. contentproviderresult; import android. content. contentvalues; import android. content. operationapplicationexception; import android. content. res. assetfiledescriptor; Import android. database. cursor; import android.net. uri; import android. OS. environment; import android. OS. parcelfiledescriptor; import android. util. log; public class testcontentprovider extends contentprovider {@ override public int Delete (URI Uri, string selection, string [] selectionargs) {// todo auto-generated method stub log. E ("H3C", "delete"); Return 0 ;}@ override Public String GetType (URI ){ // Todo auto-generated method stub log. E ("H3C", "GetType"); return NULL ;}@ override public URI insert (URI Uri, contentvalues values) {// todo auto-generated method stub log. E ("H3C", "insert"); return NULL ;}@ override public Boolean oncreate () {// todo auto-generated method stub log. E ("H3C", "CREATE"); Return false ;}@ override public cursor query (URI Uri, string [] projection, string selection, String [] selectionargs, string sortorder) {// todo auto-generated method stub log. E ("H3C", "query"); return NULL ;}@ override public int Update (URI Uri, contentvalues values, string selection, string [] selectionargs) {// todo auto-generated method stub log. E ("H3C", "Update"); Return 0 ;}@ override public assetfiledescriptor openassetfile (URI Uri, string mode) throws filenotfoundexception {// Todo auto-generated method stub log. E ("H3C", "openassetfile"); return Super. openassetfile (Uri, mode);} // This method is very important and must be rewritten. Otherwise, the filenotfound exception @ override public parcelfiledescriptor openfile (URI Uri, string mode) is reported by default) throws filenotfoundexception {// todo auto-generated method stub file root = environment. getexternalstoragedirectory (); root. mkdirs (); File Path = new file (root, Uri. getencodedpath (); log. E ("H3C", "opefile:" + path); int imode = 0; If (mode. Contains ("W") {imode | = parcelfiledescriptor. mode_write_only; If (! Path. exists () {try {path. createnewfile ();} catch (ioexception e) {e. printstacktrace () ;}} if (mode. contains ("R") imode | = parcelfiledescriptor. mode_read_only; If (mode. contains ("+") imode | = parcelfiledescriptor. mode_append; return parcelfiledescriptor. open (path, imode );}}

Notepadtestactivity. Java

Package COM. h3C. test; import Java. io. file; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; import Java. lang. reflect. invocationtargetexception; import Java. lang. reflect. method; import android. app. activity; import android. content. context; import android. content. PM. packageman Ager. namenotfoundexception; import android. content. res. assetfiledescriptor; import android.net. uri; import android. OS. bundle; import android. util. log; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; public class notepadtestactivity extends activity {@ override protected void oncreate (bundle savedinstancestate) {// todo auto-generated method stub super. onc Reate (savedinstancestate); setcontentview (R. layout. notepad); button = (button) findviewbyid (R. id. notepad); button. setonclicklistener (New onclicklistener () {@ override public void onclick (view v) {try {// directly read the file // inputstream is = getcontentresolver (). openinputstream (// URI. parse ("file:/mnt/sdcard/h3c.txt"); // file bkfile = new file ("/mnt/sdcard/h3c2.txt"); // If (! Bkfile. exists () {// bkfile. createnewfile (); //} // fileoutputstream out = new fileoutputstream (bkfile); // byte [] B = new byte [1024*5]; // 5kb // int Len; // while (LEN = is. read (B ))! =-1) {// out. write (B, 0, Len); //} // out. flush (); // is. close (); // out. close (); // directly write the file // outputstream out = getcontentresolver (). openoutputstream (// URI. parse ("file:/mnt/sdcard/h3c.txt"); // fileinputstream in = new fileinputstream (new file (// "/mnt/sdcard/h3c3.txt ")); /// byte [] B = new byte [1024*5]; // 5kb // int Len; // while (LEN = in. read (B ))! =-1) {// out. write (B, 0, Len); //} // out. flush (); // In. close (); // out. close (); // content stream write // assetfiledescriptor AFD = getcontentresolver ()//. openassetfiledescriptor (// URI. parse ("content: // COM. h3C. test/h3c.txt "), //" WR "); // inputstream in = AFD. createinputstream (); // file bkfile = new file ("/mnt/sdcard/h3c2.txt"); // If (! Bkfile. exists () {// bkfile. createnewfile (); //} // fileoutputstream out = new fileoutputstream (bkfile); // byte [] B = new byte [1024*5]; // 5kb // int Len; // while (LEN = in. read (B ))! =-1) {// out. write (B, 0, Len); //} // out. flush (); // In. close (); // out. close (); // read the content stream assetfiledescriptor AFD = getcontentresolver (). openassetfiledescriptor (URI. parse ("content: // COM. h3C. test/h3c.txt ")," WR "); outputstream out = AFD. createoutputstream (); fileinputstream in = new fileinputstream (new file ("/mnt/sdcard/h3c2.txt"); byte [] B = new byte [1024*5]; // 5kb int Len; while (LEN = In. Read (B ))! =-1) {out. write (B, 0, Len);} Out. flush (); In. close (); out. close ();} catch (filenotfoundexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();}}});}}

Related Article

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.