Android File IO Tutorial with Internal and External Storage

文章推薦指數: 80 %
投票人數:10人

No permissions are required to read or write files to internal storage for your ... For apps the target Android 10 (API level 29) or higher, a new feature ... Skiptocontent InthistutorialIwillcoverhowtocreatefilesinvariousmethodsinAndroidsuchasInternalStorage,ExternalStorage,theMediaStoreAPIandtheStorageAccessFramework. Iwillexplainthedifferencesbetweeneachofthesefilestoragemethodsandprovidesomecontextonwhentouseeach. IwillalsocoversomedetailsontheScopedStorageprivacyfeaturereleasedinAndroid10andenhancedinAndroid11forfilescreatedbyyourappinexternalstorage. IwillsharecodesamplesinthistutorialandIhavealsopublishedallthecodefromthistutorialintheGitHubrepositoryinthelinkbelow. https://github.com/learntodroid/FileIOTutorial AndroidInternalFileStorageTutorial ThissectionofthepostcontainsatutorialonhowtouseinternalstorageinAndroid.WewillcoverthefollowingtopicsinourtutorialontheuseofinternalstorageinAndroid. WhatisInternalStorageinAndroid?HowtoCreateaTextFileProgrammaticallyinInternalStorageinAndroidHowtoWriteTexttoaFileProgrammaticallyinInternalStorageinAndroidHowtoReadTextfromaFileProgrammaticallyinInternalStorageinAndroidHowtoDeleteaTextFileProgrammaticallyfromInternalStorageinAndroidHowtoViewFilesinInternalStorageusingtheAndroidDeviceFileExplorerHowtoRemoveFilesfromInternalStorageusingtheAndroidStorageUtility PleaseseeascreencapturebelowoftheAndroidappofwhatwewillbecreatinginthistutorial. WhatisInternalStorageinAndroid? InternalStorageinAndroidisusedforstoringfilesthatareonlyvisibletoyourapp.Nopermissionsarerequiredtoreadorwritefilestointernalstorageforyourapp.Ifyourappisuninstalledwithfilesininternalstorage,thesefileswillbedeletedasapartoftheuninstallationprocess. FilesininternalstorageinAndroidcaneitherbepersistentfilesorcachefiles. Cachefilesarestoredininternalstorageastemporaryfiles,theywillgetdeletedwhentheuseruninstallstheappbuttheycanalsobedeletedbeforethenbytheAndroidsystemclearingspaceinstorageorbydeletingthecachefileprogrammatically.Unlikecachefiles,persistentfilesininternalstoragecannotbedeletedbytheAndroidsystemautomatically. HowtoCreateaTextFileProgrammaticallyinInternalStorageinAndroid TocreateatextfileprogrammaticallyininternalstorageinAndroidwewillbeusingtheFileclassfromthejava.io.Filepackage. InthecodesampleIhavecreated,IamallowingtheusertoenterthenameofthefileinsideanEditTextaswellasallowingthemtouseaToggleButtontochooseiftheywantapersistentfileoracachefiletobecreatedininternalstorage. WewillusetheFileconstructorandprovidetwoparameters,thefirstisofthedatatypeFilewhichreferstothedirectorywheretheFilewecreatewillresideandthesecondparameterisofthedatatypeStringwhichwillbethenameofthefile. Forpersistentfilesininternalstorageweneedtousethe“files”directoryinsidetheinternalstoragedirectory.ToobtainthisdirectoryusethegetFilesDir()methodontheapplicationcontextwhichwillreturnaFileobjectpointingthe“files”directory. Forcachefilesininternalstorageweneedtousethe“cache”directoryinsidetheinternalstoragedirectory.ToobtainthisdirectoryusethegetCacheDir()methodontheapplicationcontextwhichwillreturnaFileobjectpointingthe“cache”directory. Beforewecreatethefile,Iwillfirstcheckwhetheritalreadyexistsusingtheexists()methodontheFileobjectwhichwillreturntrueiftheFilealreadyexistsorfalseifitdoesnotexist. Ifthefiledoesn’texist,IwillproceedtocreatethefileusingthecreateNewFile()methodontheFileobject. PleaseseethecodeexcerptbelowforprogrammaticallycreatingeitherapersistentorcachefileininternalstorageinAndroid. HowtoWriteTexttoaFileProgrammaticallyinInternalStorageinAndroid TowritetexttoafileresidingintheinternalstorageofourappprogrammaticallywewillbeusingtheFileOutputStreamclassfromthejava.io.FileOutputStreampackage. Inourcodesample,wewillbewritingthefilenamethathasbeenenteredintheEditTextbytheuserandwilldetermineifthefileisapersistentfileoracachefilebasedonthecheckedstatusoftheToggleButton. Alsoinourcodesample,theuserwillenterthetexttheywishtowriteintothefileinanEditTextandselectthe“WriteFile”buttonwhentheyarereadytowritethetexttothefile. TosetuptheFileOutputStreamforwritingthetexttothefile,wewillfirstcheckifthefileisapersistentfileorcachefileininternalstorage. IfitisapersistentfilethenwewillsetuptheFileOutputStreamusingtheopenFileOutput(String,int)methodontheapplicationcontextpassingthefilenameandtheContext.MODE_PRIVATEflagasparameters.TheContext.MODE_PRIVATEflagforthefilecreationmodemeansthecreatedfilecanonlybeaccessedbythecallingapplication. IfthefileisacachefilethenwewillsetuptheFileOutputStreambypassingaFileobjectpointingtothecachefileasaparametertotheFileOutputStreamconstructor. ThentowritethetexttothefileusingtheFileOutputStreamwewillcallthewrite(byte[])methodbypassingabytearrayasaparameterthatconsistsofthetextfromthefilecontentsEditTextencodedusingtheUTF-8formatintoabytearray. PleaseseethecodeexcerptbelowforprogrammaticallywritingtexttoeitherapersistentorcachefileininternalstorageinAndroid. HowtoReadTextfromaFileProgrammaticallyinInternalStorageinAndroid ToreadthetextfromafileresidingintheinternalstorageofourappprogrammaticallywewillbeusingtheFileInputStreamclassfromthejava.io.FileInputStreampackage. Inourcodesample,wewilloverwritethefilecontentsEditTextwiththetextreadfromthefileenteredintofilenameEditTextwhentheuserselectsthe“ReadFile”button. TosetuptheFileInputStreamforreadingthetextfromthefile,wewillfirstcheckifthefileisapersistentfileoracachefileininternalstorage. IfitisapersistentfilethenwewillsetuptheFileInputStreamusingtheopenFileInput(String)methodontheapplicationcontextpassingthefilenameasaparameter. IfthefileisacachefilethenwewillsetuptheFileInputStreambypassingaFileobjectpointingtothecachefileasaparametertotheFileInputStreamconstructor. ThenwecreatewillanInputStreamReaderfromtheFileInputStreamandusethattocreateaBufferedReaderwhichallowsustoreadfromthefileonelineatatime.WewillcreateanemptyArrayListofStringstostoreeachlineoftextfromthefile. NextwewillusetheBufferedReaderinsideawhilelooptoextracteachlineoftextoneatatimeuntilthereisnomoretext.EachlineoftextreadusingtheBufferedReaderwillbeinsertedintotheArrayListsequentially. Onceallofthelinesoftexthavebeenreadfromthefilewewillusethejoin(…)methodfromtheTextUtilsclasstocreateasingleStringoftextbyjoiningallofthelinesoftextintheArrayListtogetherwithanewlinecharacterbetweenalllinesoftext.ThiswillallowthetexttobeformattedcorrectlywhendisplayedintheEditTextcontainingthefilecontents. PleaseseethecodeexcerptbelowforprogrammaticallyreadingtextfromaeitherapersistentorcachefileininternalstorageinAndroid. HowtoDeleteaTextFileProgrammaticallyfromInternalStorageinAndroid TodeleteafileresidingintheinternalstorageofourappprogrammaticallywewillbeusingtheFileclassfromthejava.io.Filepackage. FirstwewillcreateFileobjectpointingtheFilewewanttodeletebyusingthefilenameenteredbytheuserandselectingtheappropriatefiledirectorybasedonwhetherthefileisapersistentfileoracachefile. Thenwewillusetheexists()methodontheFileobjecttoconfirmthatitexists,andifitdoesexistwewillproceedtodeleteusingthedelete()methodontheFileobject. PleaseseethecodeexcerptbelowforprogrammaticallydeletingeitherapersistentorcachefileininternalstorageinAndroid. HowtoViewFilesinInternalStorageusingtheAndroidDeviceFileExplorer TheDeviceFileExplorerisatoolavailableinAndroidStudiothatallowsyoutoviewallofthefilesontheAndroiddeviceconnectedtoAndroidStudio. TheDeviceFileExplorercanbeusedtoreadboththepersistentandcachefilesinsideinternalstorageofyourAndroidapp. ToaccesstheDeviceFileExplorerinAndroidStudioselectthe“View”menu,hoverover“ToolWindows”andselectthe“DeviceFileExplorer”menuitem. TheDeviceFileExplorerwillloadontherightsideofAndroidStudioandwilldisplayafiletreeofallofthedirectoriesandfilesontheAndroiddevice. Tolocatepersistentfilesininternalstorageofyourappnavigatethroughtothefollowingdirectory. data/data//files Tolocatecachefilesininternalstorageofyourappnavigatethroughtothefollowingdirectory. data/data//cache YoucanalsoopenanyfiletoreadinsideAndroidStudiobydoubleclickingonthefilename. HowtoRemoveFilesfromInternalStorageusingtheAndroidStorageUtility ItispossibletouseastorageutilityanAndroiddevicetoremovepersistentandcachefilesfromtheinternalstorageofyourapp. InthestorageutilityshownintheGIFbelow.ThetotalamountofstorageusedbyyourAndroidappbrokendownbytheAppsize,UserdataandCacheisshownalongwithabuttonto“Clearstorage”andabuttonto“Clearcache”. Selectingthe“Clearstorage”buttonwilldeleteallpersistentandcachefilesfromtheinternalstorageofyourapp. Selectingthe“Clearcache”buttonwilldeleteonlythecachefilesfromtheinternalstorageofyourappleavingthepersistentfilesininternalstorage. AndroidExternalFileStorageTutorial WhatisExternalStorageinAndroid? InAndroidExternalStorageisusedforstoringfilesthatotherappsareabletoaccess.Externalstorageisbetterforstoringlargerfilesthatneedtobesharedwithotherapps. Filesinexternalstoragecanbeappspecific,meaningthatwhentheappisuninstalledthesefilesinexternalstoragewillbedeleted.Appspecificfilesinexternalstoragecanbepersistentfilesorcachefiles. ForAndroid4.4(APIlevel19)andhigher,nostoragerelatedpermissionsarerequiredtoaccessappspecificdirectorieswithexternalstorage. ForappsthetargetAndroid10(APIlevel29)orhigher,anewfeaturecalledscopedstorageisappliedbydefaulttoexternalstoragewhichwillpreventotherappsfromaccessingyourappspecificfilesinexternalstorage. ScopestoragecanbedisabledbyusingtherequestLegacyExternalStorageflagandsettingitto“true”intheAndroidapp’smanifest. TolearnmoreaboutscopedstoragecheckouttheYouTubevideobelow. https://www.youtube.com/watch?v=UnJ3amzJM94 Mediafilessuchasimages,audioandvideocanbeexposedtootherappsinexternalstoragethroughtheuseoftheAndroidMediaStoreAPI. OtherfilesyouwanttosharetootherappsinexternalstoragesuchasdocumentscanbesharedusingtheStorageAccessFramework. HowtoStorePersistentandCacheFilesinExternalStorageinAndroid AppspecificpersistentfilesinexternalstorageresideinadirectoryaccessibleusingthegetExternalFileDirs()method. AppspecificcachefilesinexternalstorageresideinadirectoryaccessibleusingthegetExternalCacheDirs()method. ThecodesamplebelowcontainscodeforwritingapersistentfileoracachefileintoexternalstorageinAndroid. ThecodesamplebelowcontainscodeforreadingapersistentfileoracachefilefromexternalstorageinAndroid. BelowisascreenshotofanAndroidappcreatingapersistentfileinappspecificexternalstorage. BelowisascreenshotoftheDeviceFileExplorerinAndroidStudioshowingthepersistentfilecreatedinappspecificexternalstorage. BelowisascreenshotofanAndroidappcreatingacachefileinappspecificexternalstorage. BelowisascreenshotoftheDeviceFileExplorerinAndroidStudioshowingthecachefilecreatedinappspecificexternalstorage. HowtoStoreMediaFilesinExternalStorageinAndroid Mediafilessuchasimages,videosandaudiocanbesharedinexternalstoragewithotherappsusingtheAndroidMediaStoreAPIprovidingtheyhavetheREAD_EXTERNAL_STORAGEpermission.MediafilessharedusingtheMediaStoreAPIwillnotbedeletedwhentheappisuninstalled. OnAndroid10(APIlevel29)orhigher,READ_EXTERNAL_STORAGEorWRITE_EXTERNAL_STORAGEpermissionsarerequiredtoaccessmediafilescreatedbyotherappsviatheMediaStoreAPI.OnAndroid9(APIlevel28)orlowerpermissionsarerequiredforaccessingallmediafilesviatheMediaStoreAPI. TodemonstratehowtostoragemediafilesinexternalstorageinAndroidusingtheMediaStoreAPI,IcreatedasampleappthatloadsanimagefromtheinternetusingtheGlidelibrarythenstoresitintothePicturesdirectoryinexternalstorageusingtheMediaStoreAPIforimages. TheappalsowilldisplayaRecyclerViewinagridlayoutofallimagesinthePicturesdirectoryretrievedusingtheMediaStoreAPI. IfyouwouldliketolearnmoreabouthowtosetupanduseGlideforimageloadinginyourAndroidappincludinghowtodownloadtheGlideusingGradleandhowtosetupthemanifesttoincludeinternetpermissions,checkoutthetutorialIwroteonhowtouseGlideatthelinkbelow. AndroidGlideTutorialwithExamplesinJava ForthissectionofthetutorialfirstwewillbecreatingaclassmodellinganimageretrievedfromtheMediaStoreAPI.SeethecodesamplefortheImageclassbelow. NextwewillbecreatingaRecyclerViewHolderclassfortheImagetodisplaytheImageintheRecyclerView.SeethecodesamplefortheImageViewHolderclassbelowwhichsetsthenameoftheImageintheTextViewandloadstheImageViewwithGlideinsidethebind(Image)method. ForthenextstepwewillcreateaRecyclerViewAdapterfortheRecyclerView.SeethecodesamplefortheGalleryRecyclerAdapterclassbelow. InthefinalstepinthissectionofthetutorialwewillcreateanActivityclassthatincludescodeforinsertinganImageintotheMediaStoreAPIandqueryingImagesfromtheMediaStoreAPIintotheRecyclerViewAdaptertobeshownintheRecyclerView. HowtoStoreDocumentsinExternalStorageinAndroid DocumentsandotherfilescanbesharedwithotherappsinexternalstorageusingtheStorageAccessFramework. NopermissionsarerequiredreadorwritefilesinexternalstoragetotheStorageAccessFramework.FilescreatedusingyourappviatheStorageAccessFrameworkwillnotautomaticallybedeletedwhenyouuninstallyourapp. PleaseseethecodesamplefortheactivityclassbelowthatcanreadandwritefilestoexternalstorageusingtheStorageAccessFramework. SeethescreencapturebelowshowingtheuserexperienceofcreatingandwritingtoatextdocumentgeneratingusingtheStorageAccessFramework. Sharethispost: ShareonFacebook ShareonTwitter ShareonEmail ShareonWhatsApp RecentPosts linktoHowtoCreateaPieChartinanAndroidAppwithMPAndroidChart https://www.youtube.com/watch?v=S3zqxVoIUig AllofthecodesamplesinthispostareavailableonGitHub. CodeSamples ProjectLevelBuild.GradleFile AppLevelBuild.Gradle...ContinueReading linktoHowtoCreateaBMICalculatorAndroidApp Asapartoftheseriesforcreatingappsfromscratch,IhaveputtogetheratutorialonhowtobuildaBMIcalculatorappforAndroid. Inthistutorial,wewillbuildaBMIcalculatorappfor...ContinueReading reportthisad reportthisad AboutUs LearnToDroidisanonlineresourcefocusedonprovidingqualitycontentthathelpsourreaderslearnhowtodesign,createandmarketoutstandingappsforAndroid. ReadMore reportthisad SocialAccounts reportthisad reportthisad xx



請為這篇文章評分?