Android File IO Tutorial with Internal and External Storage
文章推薦指數: 80 %
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/
延伸文章資訊
- 1Handling Files in Code After Android 10 Released - Medium
file API in Android 10 if the Storage Access Framework does not suit your needs practically or op...
- 2How to view and manage your files in Android 10 - TechRepublic
- 3Android 10 & 11 storage cheat sheet | by Petros Douvantzis
It can read files created by other apps. You can't write to a random folder in the internal stora...
- 4Android File IO Tutorial with Internal and External Storage
No permissions are required to read or write files to internal storage for your ... For apps the ...
- 5Internal storage (ROM): Samsung GALAXY Core Prime - T-Mobile