Saving File
Android reads and writes files in the same way as normal Java IO, and the only limitation is that when we create a file we can't be as casual as javase. There are two forms of general Android read-write files:
1 file file = new file(context. Getfilesdir(), filename);
2 fileoutputstream outputstream = openfileoutput(filename, Context. Mode_private);
It is highly recommended to use the first method, because in the first way we can use many advanced points of the file reading and writing method, so that does not say that can improve efficiency, but can reduce the error probability.
Code:
Public classMainactivityextendsActivity {TextView view; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r.layout.fragment_layout); View=(TextView) Findviewbyid (R.ID.TEXTVIEW1); Button Write=(Button) Findviewbyid (R.id.button1); Write.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View arg0) {//TODO auto-generated Method StubView.settext (Getfilesdir (). toString ()); String filename= "MyFile"; String String= "Hello world!"; FileOutputStream OutputStream; Try{OutputStream=openfileoutput (filename, context.mode_append); PrintWriter PW=NewPrintWriter (OutputStream); Pw.println (string); Pw.close (); if(outputstream!=NULL) Outputstream.close (); } Catch(Exception e) {e.printstacktrace (); } } }); Button Read=(Button) Findviewbyid (R.id.button2); Read.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View arg0) {//TODO auto-generated Method StubString filename= "MyFile"; Try{BufferedReader Reader=NewBufferedReader (NewFileReader (NewFile (Getfilesdir (), filename)); String Res=""; Res=Reader.readline (); View.settext (RES); Reader.close (); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }); }}View Code
Note: There is no difference between the memory and the external memory read and write in Android, the Memory acquisition directory uses Getfiledir (), and the Save as:getexternalstoragepublicdirectory() to save the file in the External memory public Section
getExternalFilesDir()用于保存个人文件的时候使用。
In addition
getExternalStorageState()querying external storage state;
getFreeSpace()OrgetTotalSpace()查出是否有足够的可用空间;
getCacheDir()All cached files that are created on a regular basis.
Android Saving Data (ii)