Write data to internal Storage:
1String fileName = "MyFile.txt";2String str= "Saving data to internal storage";3 Try {4FileOutputStream fos =openfileoutput (FileName, context.mode_private);5 Fos.write (Str.getbytes ());6 Fos.flush ();7 fos.close ();8 9}Catch(FileNotFoundException e) {Ten e.printstacktrace (); One}Catch(IOException e) { A e.printstacktrace (); -}
Read data from internal storage:
1 Try {2FileInputStream FIS = openfileinput ("MyFile.txt");3 byte[] data =New byte[Fis.available ()];4 fis.read (data);5 fis.close ();6 7Textview.settext (NewString (data));8 9 Ten}Catch(FileNotFoundException e) { One e.printstacktrace (); A}Catch(IOException e) { - e.printstacktrace (); -}
Write data to external Storage:
<android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
1 if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {2 3 4 5File File =NewFile (Environment.getexternalstoragedirectory (), "MyFile.txt");6 7 if(!file.exists ())8 {9 Try {Ten file.createnewfile (); One}Catch(IOException e) { A e.printstacktrace (); - } - } the Try { -FileOutputStream fos =Newfileoutputstream (file); - Fos.write (Edittext.gettext (). toString (). GetBytes ()); - fos.close (); + -}Catch(FileNotFoundException e) { + e.printstacktrace (); A}Catch(IOException e) { at e.printstacktrace (); - } -}
Read data from external storage:
1 if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {2 3 4 5File File =NewFile (Environment.getexternalstoragedirectory (), "MyFile.txt");6 7 Try {8FileInputStream FIS =Newfileinputstream (file);9 byte[] data =New byte[Fis.available ()];Ten One fis.read (data); A fis.close (); - -Textview.settext (NewString (data)); the -}Catch(FileNotFoundException e) { - e.printstacktrace (); -}Catch(IOException e) { + e.printstacktrace (); - } + A}
To create a file in the cache directory:
1 Try {2File File = File.createtempfile ("Mycache", "TXT", Getcachedir ());3 4FileOutputStream fos =Newfileoutputstream (file);5 Fos.write (Edittext.gettext (). toString (). GetBytes ());6 fos.close ();7 8 9 Ten One}Catch(IOException e) { A e.printstacktrace (); -}
Android file operation