External Storage in Android with Example - GeeksforGeeks

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

External Storage in Android with Example · App-Specific storage: Store data files within internal volume directories or external. · Shared Storage ... Skiptocontent TutorialsPracticeDS&Algo.DSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesISROCSISROCSSolvedPapersISROCSOriginalPapersandOfficialKeysISROCSSyllabusforScientist/EngineerExamUGCNETCSUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobCourses ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantri HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWebDevelopmentPuzzlesProjectIdeasSchoolLearning RelatedArticles ▲RelatedArticlesExternalStorageinAndroidwithExampleCallinganExternalPrograminJavausingProcessandRuntimeProcessBuilderinJavatocreateabasiconlineJudgeJava.lang.RuntimeclassinJavaIslandofIsolationinJavaHowtomakeobjecteligibleforgarbagecollectioninJava?Mark-and-Sweep:GarbageCollectionAlgorithmGarbageCollectioninJavaRegularExpressionsinJavaMultithreadinginJavaLifecycleandStatesofaThreadinJavaMainthreadinJavaJavaConcurrency–yield(),sleep()andjoin()methodsInter-threadCommunicationinJavaJava.lang.ThreadclassinJavaWhatdoesstart()functiondoinmultithreadinginJava?JavaThreadPriorityinMultithreadingJoiningThreadsinJavaNamingathreadandfetchingnameofcurrentthreadinJavaSynchronizedinJavaMethodandBlockSynchronizationinJavaProducer-ConsumersolutionusingthreadsinJavaThreadPoolsinJavaSemaphoreinJavaJava.util.concurrent.SemaphoreclassinJavaBottomNavigationBarinAndroidHowtoChangetheBackgroundColorofButtoninAndroidusingColorStateList?AndroidTutorialAndroidArchitectureServicesinAndroidwithExampleTableofContentsExternalStorageinAndroidwithExampleCallinganExternalPrograminJavausingProcessandRuntimeProcessBuilderinJavatocreateabasiconlineJudgeJava.lang.RuntimeclassinJavaIslandofIsolationinJavaHowtomakeobjecteligibleforgarbagecollectioninJava?Mark-and-Sweep:GarbageCollectionAlgorithmGarbageCollectioninJavaRegularExpressionsinJavaMultithreadinginJavaLifecycleandStatesofaThreadinJavaMainthreadinJavaJavaConcurrency–yield(),sleep()andjoin()methodsInter-threadCommunicationinJavaJava.lang.ThreadclassinJavaWhatdoesstart()functiondoinmultithreadinginJava?JavaThreadPriorityinMultithreadingJoiningThreadsinJavaNamingathreadandfetchingnameofcurrentthreadinJavaSynchronizedinJavaMethodandBlockSynchronizationinJavaProducer-ConsumersolutionusingthreadsinJavaThreadPoolsinJavaSemaphoreinJavaJava.util.concurrent.SemaphoreclassinJavaBottomNavigationBarinAndroidHowtoChangetheBackgroundColorofButtoninAndroidusingColorStateList?AndroidTutorialAndroidArchitectureServicesinAndroidwithExampleSaveArticle ImproveArticle SaveArticle LikeArticle ExternalStorageinAndroidwithExampleDifficultyLevel: MediumLastUpdated: 02Nov,2020Androidgivesvariousoptionsforstoringappsdatawhichusesafilesystemsimilartothedisk-basedsystemoncomputerplatformsApp-Specificstorage:Storedatafileswithininternalvolumedirectoriesorexternal.Thesedatafilesaremeantonlyfortheapp’suse.Itusesinternalstoragedirectoriestosavesensitiveinformationsuchasausernameandpasswordthatotherappshouldnotaccess.SharedStorage:Storedatafilessuchasimages,audio,video,documents,etc.thattheappmayneedtosharewithotherapps.SharedPreferences:Storeprimitivedatatypesuchasinteger,float,boolean,string,longinkey-valuepairs.Databases:Storestructureddatasuchasuser-information(name, age,phone,email,address,etc.)intoprivatedatabases.Developersareadvisedtousetheoptionsavailabletostoredatadependinguponthespacerequired,reliabledataaccess,andprivacyofdata.ThedatafilessavedoverexternalstoragedevicesarepubliclyaccessibleonsharedexternalstorageusingUSBmassstoragetransfer.DatafilesstoredoverexternalstorageusingaFileOutputStreamobjectandcanbereadusingaFileInputStreamobject.Wantamorefast-paced&competitiveenvironmenttolearnthefundamentalsofAndroid?Clickheretoheadtoaguideuniquelycuratedbyourexpertswiththeaimtomakeyouindustryreadyinnotime!ExternalStorageAvailabilityInordertoavoidcrashingtheappfirst,weneedtocheckstorageSDCardisavailableforreadingandwriteoperations.ThemethodgetExternalStorageState()isusedtodeterminethestateofmountedstoragemediasuchasSDCardismissing,read-onlyorreadable,andwritable.Belowisthecodesnippetwhichwewillusetochecktheavailabilityofexternalstorage.JavabooleanisAvailable=false;booleanisWritable=false;booleanisReadable=false;Stringstate=Environment.getExternalStorageState();  if(Environment.MEDIA_MOUNTED.equals(state)){  //Operationpossible-ReadandWrite  isAvailable=true;  isWritable=true;  isReadable=true;}elseif(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){      //Operationpossible-ReadOnly      isAvailable=true;      isWritable=false;      isReadable=true;}else{      //SDcardnotavailable      isAvailable=false;      isWritable=false;      isReadable=false; }MethodstoStoredatainExternalStoragegetExternalStoragePublicDirectory():Thisisthepresentrecommendedmethodtokeepfilespublicandthesefilesarenotdeletedevenwhentheappisuninstalledfromthesystem.Foreg:Imagesclickedbythecameraarestillavailableevenafterweuninstallthecamera.getExternalFilesDir(Stringtype):Thismethodisusedtostoreprivatedatathatarespecifictotheapponly.Anddataareremovedasweuninstalltheapp.getExternalStorageDirectory():Thismethodisnotrecommended.Itisnowabsoluteanditisusedtoaccessexternalstorageinolderversions,APILevellessthan7.ExampleInthisexample,wewouldstoretextdataintotheexternalstorageandfetchtoseethatdata.AsampleGIFisgivenbelowtogetanideaaboutwhatwearegoingtodointhisarticle.NotethatwearegoingtoimplementthisprojectusingtheJavalanguage. StepbyStepImplementationStep1:CreateaNewProjectTocreateanewprojectinAndroidStudiopleaserefertoHowtoCreate/StartaNewProjectinAndroidStudio.NotethatselectJavaastheprogramminglanguage.Step2:AccessPermissiontoExternalStorageToreadandwritedatatoexternalstorage,theapprequiredWRITE_EXTERNAL_STORAGEandREAD_EXTERNAL_STORAGEsystempermission.ThesepermissionsareaddedtotheAndroidManifest.xmlfile.Addthesepermissionsjustafterthepackagename.XML                                  ...            Step3:Beforecreatingthelayoutandcorrespondingjavafileslet’saddafewstringattributeswhichweareusinginourlayoutfilesGotoapp>res>values>string.xmlandinsertthefollowingcodesnippetXML  ...    EntertheTextData    Enteryourinformation    ViewInformation    SavePublicly    SavePrivately      SavedTextData    Clicktoviewsavedinformation    GoBack    PublicData    PrivateData  ...Nowgotoapp>res>values>colors.xmlandchangethecolorattributesasfollowinginordertomakeAppBarmoreattractive.XML       #0F9D58    #16E37F    #03DAC5      #0F9D58    #FFFFFFAgaingotoapp>res>drawableandcreateanewDrawableResourceFileandnameitasbutton_layout.Inthis,wearemodifyingourbuttonstyleforabetterUX/UI.XML                          Step4:Workingwiththeactivity_main.xmlfileGotores>layout>activity_main.xmlandwritedownthefollowingcode.Inthislayoutfile,wearecreatingamultilineEditTextViewforgettingthedatafromusersandButtonstosavethatdataoverinternalandexternalstoragemedia.XML                                Step5:WorkingwiththeMainActivity.javafileInMainActivitywedefinethefunctionsthathandledtheonClickbehaviorofthebuttons.AndfetchthedatafromtheEditTextandsaveitinexternalstoragepubliclyandprivately.WealsodisplayaToastmessageofthepathwherethedataisstored.Javaimportandroid.Manifest;importandroid.content.Intent;importandroid.os.Bundle;importandroid.os.Environment;importandroid.view.View;importandroid.widget.EditText;importandroid.widget.Toast;importandroidx.appcompat.app.AppCompatActivity;importandroidx.core.app.ActivityCompat;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;  publicclassMainActivityextendsAppCompatActivity{      //AfterAPI23thepermissionrequestforaccessingexternalstorageischanged    //BeforeAPI23permissionrequestisaskedbytheuserduringinstallationofapp    //AfterAPI23permissionrequestisaskedatruntime    privateintEXTERNAL_STORAGE_PERMISSION_CODE=23;    EditTexteditText;      @Override    protectedvoidonCreate(BundlesavedInstanceState){        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                  //findViewByIdreturnaview,weneedtocastittoEditTextView        editText=(EditText)findViewById(R.id.editText_data);    }      publicvoidsavePublicly(Viewview){        //RequestingPermissiontoaccessExternalStorage        ActivityCompat.requestPermissions(this,newString[]{Manifest.permission.READ_EXTERNAL_STORAGE},                 EXTERNAL_STORAGE_PERMISSION_CODE);        StringeditTextData=editText.getText().toString();                  //getExternalStoragePublicDirectory()representsrootofexternalstorage,weareusingDOWNLOADS        //Wecanusefollowingdirectories:MUSIC,PODCASTS,ALARMS,RINGTONES,NOTIFICATIONS,PICTURES,MOVIES        Filefolder=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);                  //StoringthedatainfilewithnameasgeeksData.txt        Filefile=newFile(folder,"geeksData.txt");        writeTextData(file,editTextData);        editText.setText("");    }      publicvoidsavePrivately(Viewview){        StringeditTextData=editText.getText().toString();                  //CreatingfolderwithnameGeekForGeeks        Filefolder=getExternalFilesDir("GeeksForGeeks");                  //Creatingfilewithnamegfg.txt        Filefile=newFile(folder,"gfg.txt");        writeTextData(file,editTextData);        editText.setText("");    }      publicvoidviewInformation(Viewview){        //Creatinganintenttostartanewactivity        Intentintent=newIntent(MainActivity.this,ViewInformationActivity.class);        startActivity(intent);    }      //writeTextData()methodsavethedataintothefileinbyteformat    //Italsotoastamessage"Done/filepath_where_the_file_is_saved"    privatevoidwriteTextData(Filefile,Stringdata){        FileOutputStreamfileOutputStream=null;        try{            fileOutputStream=newFileOutputStream(file);            fileOutputStream.write(data.getBytes());            Toast.makeText(this,"Done"+file.getAbsolutePath(),Toast.LENGTH_SHORT).show();        }catch(Exceptione){            e.printStackTrace();        }finally{            if(fileOutputStream!=null){                try{                    fileOutputStream.close();                }catch(IOExceptione){                    e.printStackTrace();                }            }        }    }}Step6:CreateanewEmptyActivityWewillcreateanewactivityandnameitViewInformationActivity.Weusethisactivitytodisplaythesaveddatafromtheexternalstorage.So,first,wecreatealayoutforthisactivitysimilartotheMainActivitylayout.activity_view_information.xmllayoutcodesnippet:XML                                Now,wewillcreateacorrespondingjavacodeforViewInformationActivity.Inthis,wedefinemethodsshowPublicData()andshowPrivateData()overbuttonsthatwillfetchthedatafromthefilessavedtoexternalstorageandaddthedatatobuffer,andthenpopulatethedatatoTextViewinordertoshowthem.ViewInformationAcitity.javacodesnippet:Javaimportandroid.content.Intent;importandroid.os.Bundle;importandroid.os.Environment;importandroid.view.View;importandroid.widget.TextView;importandroidx.appcompat.app.AppCompatActivity;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;  publicclassViewInformationActivityextendsAppCompatActivity{      TextViewtextView;      @Override    protectedvoidonCreate(BundlesavedInstanceState){        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_view_information);                  //findViewByIdreturnsaview,weneedtocastitintoTextView        textView=(TextView)findViewById(R.id.textView_get_saved_data);    }      publicvoidshowPublicData(Viewview){        //Accessingthesaveddatafromthedownloadsfolder        Filefolder=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);                  //geeksDatarepresentthefiledatathatissavedpublicly        Filefile=newFile(folder,"geeksData.txt");        Stringdata=getdata(file);        if(data!=null){            textView.setText(data);        }else{            textView.setText("NoDataFound");        }    }      publicvoidshowPrivateData(Viewview){                  //GeeksForGeeksrepresentthefoldernametoaccessprivatelysaveddata        Filefolder=getExternalFilesDir("GeeksForGeeks");                  //gft.txtisthefilethatissavedprivately        Filefile=newFile(folder,"gfg.txt");        Stringdata=getdata(file);        if(data!=null){            textView.setText(data);        }else{            textView.setText("NoDataFound");        }    }      publicvoidback(Viewview){        Intentintent=newIntent(ViewInformationActivity.this,MainActivity.class);        startActivity(intent);    }      //getdata()isthemethodwhichreadsthedata    //thedatathatissavedinbyteformatinthefile    privateStringgetdata(Filemyfile){        FileInputStreamfileInputStream=null;        try{            fileInputStream=newFileInputStream(myfile);            inti=-1;            StringBufferbuffer=newStringBuffer();            while((i=fileInputStream.read())!=-1){                buffer.append((char)i);            }            returnbuffer.toString();        }catch(Exceptione){            e.printStackTrace();        }finally{            if(fileInputStream!=null){                try{                    fileInputStream.close();                }catch(IOExceptione){                    e.printStackTrace();                }            }        }        returnnull;    }}Output:RunonEmulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201101122556/External-Storage-Tutorial-in-Android.mp4MyPersonalNotes arrow_drop_upSave LikeNext CallinganExternalPrograminJavausingProcessandRuntimeRecommendedArticlesPage:26,Oct2029,Oct2002,May2109,Jul2120,Feb2125,Jul2124,Sep2125,Nov1917,Nov2114,Apr1707,Jan1920,Nov1913,Sep2108,Apr2125,Nov2016,May2023,Aug2022,Jan2110,Apr2116,Jul1825,Oct2005,May2114,Oct1916,Dec19ArticleContributedBy:ankur035@ankur035VotefordifficultyCurrentdifficulty: MediumEasy Normal Medium Hard ExpertArticleTags:androidTechnicalScripter2020AndroidJavaTechnicalScripterPracticeTags:JavaAndroidReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinAndroidMVVM(ModelViewViewModel)ArchitecturePatterninAndroidFix"UnabletolocateadbwithinSDK"inAndroidStudioHowtoCreateandAddDatatoSQLiteDatabaseinAndroid?HowtoUpdateGradleinAndroidStudio?HowtoFix“FailedtoinstallthefollowingAndroidSDKpackagesassomelicenseshavenotbeenaccepted”ErrorinAndroidStudio?MostvisitedinJavaArraysinJavaFor-eachloopinJavaSplit()StringmethodinJavawithexamplesObjectOrientedProgramming(OOPs)ConceptinJavaArrays.sort()inJavawithexamples× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt!



請為這篇文章評分?