Learn android from scratch (Data Storage (2) Internal Storage. 36 .)
- Call
openFileOutput()
With the name of the file and the operating mode. This returnsFileOutputStream
. PassOpenFileOutput () creates a FileoutputStream object
- Write to the file
write()
. Create a Write object and perform data read/Write operations.
- Close the stream
close()
. Close the link.The above describes the basic steps for saving data files to internal storage.
The following code is used to explain
Xml file
JAVA filesPackage com. example. internalstorage; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import android. app. activity; import android. content. context; import android. OS. bundle; import android. util. log; import android. view. view; import android. widget. button; import android. widget. toast; public class MainActivity extends Activity {priv Ate Button saveData, getData; private static final String FILENAME = "flyou.txt"; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); saveData = (Button) this. findViewById (R. id. button1); getData = (Button) this. findViewById (R. id. button2); saveData. setOnClickListener (new View. onClickListener () {// save information @ Overridepublic void onCli Ck (View v) {// TODO Auto-generated method stubFileOutputStream out = null; try {String infoString = ""; out = openFileOutput (FILENAME, Context. MODE_PRIVATE); out. write (infoString. getBytes (); Toast. makeText (MainActivity. this, "data saved successfully", 2 ). show ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {if (out! = Null) {out. close () ;}} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}}); // read the information getData. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubFileInputStream input = null; try {input = openFileInput (FILENAME ); byte [] data = new byte [1024]; int len = input. read (data); input. close (); // System. out. println (new String (data, 0, len); Toast. makeText (MainActivity. this, new String (data, 0, len), 2 ). show ();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}});}}
Open Information
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140829/20140829091144210.png" alt = "\">
View information in a file browser
Export files
Open with notepad
The above operations can easily implement the internal storage process of files.
The official api also provides instructions on how to store cached files.
Next forecast:
External Storage