Android - Internal Storage - Tutorialspoint

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

Android provides many kinds of storage for applications to store their data. These storage places are shared preferences, internal and external storage, ... AndroidBasics Android-Home Android-Overview Android-EnvironmentSetup Android-Architecture Android-ApplicationComponents Android-HelloWorldExample Android-Resources Android-Activities Android-Services Android-BroadcastReceivers Android-ContentProviders Android-Fragments Android-Intents/Filters Android-UserInterface Android-UILayouts Android-UIControls Android-EventHandling Android-StylesandThemes Android-CustomComponents AndroidAdvancedConcepts Android-DragandDrop Android-Notifications LocationBasedServices Android-SendingEmail Android-SendingSMS Android-PhoneCalls PublishingAndroidApplication AndroidUsefulExamples Android-AlertDialoges Android-Animations Android-AudioCapture Android-AudioManager Android-AutoComplete Android-BestPractices Android-Bluetooth Android-Camera Android-Clipboard Android-CustomFonts Android-DataBackup Android-DeveloperTools Android-Emulator Android-FacebookIntegration Android-Gestures Android-GoogleMaps Android-ImageEffects Android-ImageSwitcher Android-InternalStorage Android-JetPlayer Android-JSONParser Android-LinkedinIntegration Android-LoadingSpinner Android-Localization Android-LoginScreen Android-MediaPlayer Android-Multitouch Android-Navigation Android-NetworkConnection Android-NFCGuide Android-PHP/MySQL Android-ProgressCircle Android-ProgressBar Android-PushNotification Android-RenderScript Android-RSSReader Android-ScreenCast Android-SDKManager Android-Sensors Android-SessionManagement Android-SharedPreferences Android-SIPProtocol Android-SpellingChecker Android-SQLiteDatabase Android-SupportLibrary Android-Testing Android-TexttoSpeech Android-TextureView Android-TwitterIntegration Android-UIDesign Android-UIPatterns Android-UITesting Android-WebViewLayout Android-Wi-Fi Android-Widgets Android-XMLParsers AndroidUsefulResources Android-QuestionsandAnswers Android-UsefulResources Android-Discussion SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho Android-InternalStorage Advertisements PreviousPage NextPage  Androidprovidesmanykindsofstorageforapplicationstostoretheirdata.Thesestorageplacesaresharedpreferences,internalandexternalstorage,SQLitestorage,andstoragevianetworkconnection. Inthischapterwearegoingtolookattheinternalstorage.Internalstorageisthestorageoftheprivatedataonthedevicememory. Bydefaultthesefilesareprivateandareaccessedbyonlyyourapplicationandgetdeleted,whenuserdeleteyourapplication. Writingfile Inordertouseinternalstoragetowritesomedatainthefile,calltheopenFileOutput()methodwiththenameofthefileandthemode.Themodecouldbeprivate,publice.t.c.Itssyntaxisgivenbelow− FileOutputStreamfOut=openFileOutput("filenamehere",MODE_WORLD_READABLE); ThemethodopenFileOutput()returnsaninstanceofFileOutputStream.SoyoureceiveitintheobjectofFileInputStream.Afterthatyoucancallwritemethodtowritedataonthefile.Itssyntaxisgivenbelow− Stringstr="data"; fOut.write(str.getBytes()); fOut.close(); Readingfile Inordertoreadfromthefileyoujustcreated,calltheopenFileInput()methodwiththenameofthefile.ItreturnsaninstanceofFileInputStream.Itssyntaxisgivenbelow− FileInputStreamfin=openFileInput(file); Afterthat,youcancallreadmethodtoreadonecharacteratatimefromthefileandthenyoucanprintit.Itssyntaxisgivenbelow− intc; Stringtemp=""; while((c=fin.read())!=-1){ temp=temp+Character.toString((char)c); } //stringtempcontainsallthedataofthefile. fin.close(); Apartfromthethemethodsofwriteandclose,thereareothermethodsprovidedbytheFileOutputStreamclassforbetterwritingfiles.Thesemethodsarelistedbelow− Sr.No Method&description 1 FileOutputStream(Filefile,booleanappend) ThismethodconstructsanewFileOutputStreamthatwritestofile. 2 getChannel() Thismethodreturnsawrite-onlyFileChannelthatsharesitspositionwiththisstream 3 getFD() Thismethodreturnstheunderlyingfiledescriptor 4 write(byte[]buffer,intbyteOffset,intbyteCount) ThismethodWritescountbytesfromthebytearraybufferstartingatpositionoffsettothisstream Apartfromthethemethodsofreadandclose,thereareothermethodsprovidedbytheFileInputStreamclassforbetterreadingfiles.Thesemethodsarelistedbelow− Sr.No Method&description 1 available() Thismethodreturnsanestimatednumberofbytesthatcanbereadorskippedwithoutblockingformoreinput 2 getChannel() Thismethodreturnsaread-onlyFileChannelthatsharesitspositionwiththisstream 3 getFD() Thismethodreturnstheunderlyingfiledescriptor 4 read(byte[]buffer,intbyteOffset,intbyteCount) Thismethodreadsatmostlengthbytesfromthisstreamandstorestheminthebytearraybstartingatoffset Example Hereisanexampledemonstratingtheuseofinternalstoragetostoreandreadfiles.Itcreatesabasicstorageapplicationthatallowsyoutoreadandwritefrominternalstorage. Toexperimentwiththisexample,youcanrunthisonanactualdeviceorinanemulator. Steps Description 1 YouwilluseAndroidStudioIDEtocreateanAndroidapplicationunderapackagecom.example.sairamkrishna.myapplication. 2 Modifysrc/MainActivity.javafiletoaddnecessarycode. 3 Modifytheres/layout/activity_maintoaddrespectiveXMLcomponents 4 Runtheapplicationandchoosearunningandroiddeviceandinstalltheapplicationonitandverifytheresults Followingisthecontentofthemodifiedmainactivityfilesrc/MainActivity.java. packagecom.example.sairamkrishna.myapplication; importandroid.app.Activity; importandroid.os.Bundle; importandroid.view.View; importandroid.widget.Button; importandroid.widget.EditText; importandroid.widget.TextView; importandroid.widget.Toast; importjava.io.FileInputStream; importjava.io.FileOutputStream; publicclassMainActivityextendsActivity{ Buttonb1,b2; TextViewtv; EditTexted1; Stringdata; privateStringfile="mydata"; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); b2=(Button)findViewById(R.id.button2); ed1=(EditText)findViewById(R.id.editText); tv=(TextView)findViewById(R.id.textView2); b1.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewv){ data=ed1.getText().toString(); try{ FileOutputStreamfOut=openFileOutput(file,MODE_WORLD_READABLE); fOut.write(data.getBytes()); fOut.close(); Toast.makeText(getBaseContext(),"filesaved",Toast.LENGTH_SHORT).show(); } catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } }); b2.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewv){ try{ FileInputStreamfin=openFileInput(file); intc; Stringtemp=""; while((c=fin.read())!=-1){ temp=temp+Character.toString((char)c); } tv.setText(temp); Toast.makeText(getBaseContext(),"fileread",Toast.LENGTH_SHORT).show(); } catch(Exceptione){ } } }); } } Followingisthemodifiedcontentofthexmlres/layout/activity_main.xml. Inthefollowingcodeabcindicatesthelogooftutorialspoint.com Followingisthecontentoftheres/values/string.xml. MyApplication FollowingisthecontentofAndroidManifest.xmlfile. Let'strytorunourStorageapplicationwejustmodified.IassumeyouhadcreatedyourAVDwhiledoingenvironmentsetup.ToruntheappfromAndroidstudio,openoneofyourproject'sactivityfilesandclickRuniconfromthetoolbar.AndroidstudioinstallstheapponyourAVDandstartsitandifeverythingisfinewithyourset-upandapplication,itwilldisplayfollowingEmulatorwindow− Nowwhatyouneedtodoistoenteranytextinthefield.Forexample,ihaveenteredsometext.Pressthesavebutton.ThefollowingnotificationwouldappearinyouAVD− Nowwhenyoupresstheloadbutton,theapplicationwillreadthefile,anddisplaythedata.Incaseofour,followingdatawouldbereturned− NoteyoucanactuallyviewthisfilebyswitchingtoDDMStab.InDDMS,selectfileexplorerandnavigatethispath. tools>android>androiddeviceMonitor Thishasalsobeenshownintheimagebelow. PreviousPage PrintPage NextPage  Advertisements Print  AddNotes  Bookmarkthispage  ReportError  Suggestions Save Close Dashboard Logout



請為這篇文章評分?