Internal or External storage for editable app-specific file

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

Internal storage is best when you want to be sure that neither the user nor other apps can access your files. External storae : External storage ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore InternalorExternalstorageforeditableapp-specificfile AskQuestion Asked 3years,5monthsago Active 3years,5monthsago Viewed 2ktimes 2 Iamcreatinganappthatrequieranapp-specificfilethatIcalled"conf.cfg"forexample.thisfileneedtobereadbymyapplicationtocreatesomeobjectetc...thebodyofthefilelooklikethat: #activation,level,type,regexorarray 0,"critic",0,"\\d{4}\\w\\d{3}" 1,"critic",1,[word1,word2] 1,"minor",0,"\\d{2}-\\w{3}-\\d{4}\\s?\\/?\\s?\\d{2}:\\d{2}" DoingmyresearchIfoundthatthereistwotypeofStorageinandroid: Internalstorage: Internalstorageisbestwhenyouwanttobesurethatneithertheusernorotherappscanaccessyourfiles. Externalstorae: Externalstorageisthebestplaceforfilesthatdon'trequireaccessrestrictionsandforfilesthatyouwanttosharewithotherappsorallowtheusertoaccesswithacomputer. AsIwanttheusertobeabletoedit/download/upload/USEthisfile,ExternalStorageseemstobeagoodchoice.HoweveronDevelopperAndroidtheysaid: Caution:TheexternalstoragemightbecomeunavailableiftheuserremovestheSDcardorconnectsthedevicetoacomputer.AndthefilesarestillvisibletotheuserandotherappsthathavetheREAD_EXTERNAL_STORAGEpermission.Soifyourapp'sfunctionalitydependsonthesefilesoryouneedtocompletelyrestrictaccess,youshouldinsteadwriteyourfilestotheinternalstorage. Caution:Filesonexternalstoragearenotalwaysaccessible,becauseuserscanmounttheexternalstoragetoacomputerforuseasastoragedevice.Soifyouneedtostorefilesthatarecriticaltoyourapp'sfunctionality,youshouldinsteadstorethemoninternalstorage. Asthisfileneedtobealwaysavailableandiscriticaltomyapp'sfunctionality So...InternalStorageseemstobebetter.ButIneedtheusertoseeandbeabletousethefile.AndhereI'mstuck. Anyonehasanideaofwhereandhowtoput/createthisfile? EDIT:following@greenappsanswer heerisapieceofcodeI'vewrote.IusethegetExternalFilesDir(null)commandtowriteandstoremyfile StringfolderName="Innovation"; StringconfFileName="conf.txt"; StringcommentSymbol="#"; StringcommentLine=commentSymbol+"activation,level,type,regexorarray"; Filestorage=getExternalFilesDir(null); Filefolder=newFile(storage,folderName); Fileconf=newFile(folder,confFileName); Log.d(TAG,"Folderaction!"); if(!folder.exists()){ if(folder.mkdirs()){ Log.d(TAG,"Created:"+folder.getAbsolutePath()); }else{ Log.e(TAG,"foldernotcreated!"); } } Log.d(TAG,"Fileaction!"); if(!conf.exists()){ try{ Log.d(TAG,"opening..."); FileOutputStreamfos=newFileOutputStream(conf); fos.write(commentLine.getBytes()); fos.close(); Log.d(TAG,"Created:"+conf.getAbsolutePath()); }catch(IOExceptione){ e.printStackTrace(); } } if(conf.exists()){ Log.d(TAG,"Fileexistat:"+conf.getAbsolutePath()); } thefileiscreated,asshownbythelastlog Created:/storage/emulated/0/Android/data/com.aralex.innovation/files/Innovation/conf.txt ButwhenIsearchthefilewiththenativefileexplorerapplicationofthephone,Ican'tfindit.Icangotothefilefolderbutthefolder"Innovation/"ishidden. ThisisaproblembecauseIwantthefiletobevisible. Phone:Samsungs7,s7edge,s9+ DefaultFileExplorerIcon DefaultFileExplorerOppened androidfilestorage Share Follow editedJun4'18at9:03 ArnauldAlex askedJun1'18at8:34 ArnauldAlexArnauldAlex 30911goldbadge22silverbadges1313bronzebadges 14 Internalorexternalstoragearebothpossible.Alldeviceshaveit.TheyhavenothingtodowitharemovablemicroSDcard.Youreadedanolddoc. – greenapps Jun1'18at8:42 butitsays:TheexternalstoragemightbecomeunavailableiftheuserremovestheSDcardorconnectsthedevicetoacomputer – ArnauldAlex Jun1'18at8:44 Whatisunclearinyourstoryishowthisfilewouldlandonmydeviceifiinstalledyourapponit. – greenapps Jun1'18at8:45 Yesyoureadedanolddoc.Externalstorageisalwaysavailable.Pleaserereadmycomment. – greenapps Jun1'18at8:46 Ifit'sthefirstinstallationthenthefileiscreatedwithonlythefirstline(theonethatbeginsby"#").Thenuserhavetobeabletoeditthisfile(withanotherapponhisphone,likeasimplenotepad)orbeabletogowithhisphonefileexplorertothefile,replaceitetc...likeafilesimplefileonacomputer – ArnauldAlex Jun1'18at8:48  |  Show9morecomments 2Answers 2 Active Oldest Votes 1 WellIfinallyfoundananswermyself. OnthispostAndroidcreatefoldersinInternalMemory@prodevspecifythatEnvironment.getExternalStorageDirectory()isagoodplace,becausethefilewillbeaccessibleand: notethatExternalStorageinEnvironment.getExternalStorageDirectory()doesnotnecessarilyreferstosdcard,itreturnsphoneprimarystoragememory itrequirespermissions(onlyforbuildversion>=M): Sohereisacodetoanswermyproblem(itaskpermissiononruntime): privateArrayListruleList; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); [...] //Checkforthestoragepermissionbeforeaccessingthecamera.Ifthe //permissionisnotgrantedyet,requestpermission. if(hasPermissions(this,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE) ||Build.VERSION.SDK_INTActivityCompat.requestPermissions(thisActivity,permissions, RC_HANDLE_EXTERNAL_PERM); Snackbar.make(findViewById(android.R.id.content),R.string.permission_storage_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.ok,listener) .show(); } @Override publicvoidonRequestPermissionsResult(intrequestCode, @NonNullString[]permissions, @NonNullint[]grantResults){ if(requestCode!=RC_HANDLE_EXTERNAL_PERM){ Log.d(TAG,"Gotunexpectedpermissionresult:"+requestCode); super.onRequestPermissionsResult(requestCode,permissions,grantResults); return; } if(grantResults.length!=0&&grantResults[0]==PackageManager.PERMISSION_GRANTED &&grantResults[1]==PackageManager.PERMISSION_GRANTED){ Log.d(TAG,"Storagepermissiongranted"); //Wehavepermission ruleList=createRules(); return; } Log.e(TAG,"Permissionnotgranted:resultslen="+grantResults.length+ "Resultcode="+(grantResults.length>1?grantResults[0]+""+grantResults[1]:grantResults.length>0?grantResults[0]:"(empty)")); DialogInterface.OnClickListenerlistener=(dialog,id)->finish(); AlertDialog.Builderbuilder=newAlertDialog.Builder(this); builder.setTitle("AssistingTool") .setMessage(R.string.no_storage_permission) .setPositiveButton(R.string.ok,listener) .show(); } privateArrayListcreateRules(){ Log.d(TAG,"=========================READINGFILE======================"); ArrayListruleList=newArrayList<>(); StringfolderName="Innovation"; StringconfFileName="conf.txt"; StringcommentSymbol="#"; StringcommentLine=commentSymbol+"activation,level,type,regexorarray"; Filestorage=Environment.getExternalStorageDirectory(); Filefolder=newFile(storage,folderName); Fileconf=newFile(folder,confFileName); Log.d(TAG,"Folderaction!"); if(!folder.exists()){ if(folder.mkdirs()){ Log.d(TAG,"Created:"+folder.getAbsolutePath()); }else{ Log.e(TAG,"foldernotcreated!"); } } Log.d(TAG,"Fileaction!"); if(!conf.exists()){ try{ Log.d(TAG,"opening..."); FileOutputStreamfos=newFileOutputStream(conf); fos.write(commentLine.getBytes()); fos.close(); Log.d(TAG,"Created:"+conf.getAbsolutePath()); }catch(IOExceptione){ e.printStackTrace(); } } if(conf.exists()){ Log.d(TAG,"Fileexistat:"+conf.getAbsolutePath()); }else{ Log.e(TAG,"Thefiledoesn'texist..."); } } Nowitcreateaapp-specificfile /storage/emulated/0/Innovation/conf.txt thatisaccessiblebyuser! Share Follow answeredJun4'18at10:02 ArnauldAlexArnauldAlex 30911goldbadge22silverbadges1313bronzebadges 1 1 Allyousaymakesnosense.getExternalFilesDir()shouldworktoo.Andwithouttheneedforpermissions. – greenapps Jun4'18at10:08 Addacomment  |  0 Soexternalstorage. Nointernalasfileexplorershavenoaccesstoyourappsprivateinternalmemory. YoucouldusegetExternalFilesDir(null)asthenyoudontneedreadandwritepermissions Share Follow answeredJun1'18at9:07 greenappsgreenapps 10.9k22goldbadges1313silverbadges1919bronzebadges 2 butasissaid,ifthefileisnot"there"Ihavetocreateit.SoIneedawritepermission – ArnauldAlex Jun1'18at9:09 seeEditinmainpost – ArnauldAlex Jun4'18at8:32 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedandroidfilestorageoraskyourownquestion. TheOverflowBlog Whoownsthisoutage?BuildingintelligentescalationchainsformodernSRE Podcast395:Whoisbuildingcloudsfortheindependentdeveloper? FeaturedonMeta Nowlive:Afullyresponsiveprofile Reducingtheweightofourfooter TwoBornottwoB-Farewell,BoltClockandBhargav! Linked 17 AndroidcreatefoldersinInternalMemory Related 34 Howtomove/renamefilefrominternalappstoragetoexternalstorageonAndroid? 56 WhatarethedifferencesamongInternalstorage,externalstorage,sdcardandremovablestorage? 90 Androidsavingfiletoexternalstorage 0 what'sthedifferencebetweenandroidinternalstorageandexternal-privatestorage? 0 AndroidFileStorageOptions-External+Internal 0 Getinternalaswellasexternalstoragefilepath 854 android.os.FileUriExposedException:file:///storage/emulated/0/test.txtexposedbeyondappthroughIntent.getData() HotNetworkQuestions CollectingalternativeproofsfortheoddityofCatalan MethodforcreateacopyofList Projectingshadows,orevenamovie,onthemoon StrangeconditionalSyntaxinTSQLQuery:"<=+"Whatdoesitdo? WhatistheBiblicalbasisforthebeliefthatTrinitarianbeliefis“not”requiredforsalvation? WhyistheSecondAmendmentstructureddifferentlyfromallotheramendments? HowdoIgettothisislandinthemiddleofnowhereinthenorth-eastsectionofthemap? Couldsiliconbasedlifeformseatcarbonbasedfood Willone-cellbrainfuckhalt? Howtoaligntexttothetopofatabularcell? WhatCouldExplainASolitaryMountaininaGrassland? meaningof"ruinsomethingforsomeone" DoesaserverneedaGPU? NewtoBikes:MychainfelloffandIputitbackon.HowcanIknowifit'sontherightcog? Isitharmfulltoheatawhetstone Wordforaplanthathasnotbeenperformedbecauseofsomeissues CanImakeahelixwith4strands? HowtoannotatestaffwithbeatnumbersinLilypond? Whatdoes'dosteakandchips'mean? compassandstraightedgeinacientGreek? HowcanIgettrue1"thickoakboards? ConvertRegextoMask Sci-fistorywherepeoplearereincarnatedathubsandamanwantstofigureoutwhatishappening HowdoIdownloadthedesktopversionofUbuntu21.10forARM? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. default Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?