android-file Storage

Source: Internet
Author: User

Target effect:

The program runs, displays an input box and button, the input box input content Click button will prompt to save the success, close the program, open again in the input box to display the content just entered, and prompt English.


1.activity_main.xml the page to place two controls.

Activity_main.xml page:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    tools:context= ". Mainactivity ">    <edittext        android:id=" @+id/etinput "        android:layout_width=" Wrap_content        " android:layout_height= "Wrap_content"        android:layout_above= "@+id/btclick"        android:layout_ Centerhorizontal= "true"        android:layout_marginbottom= "34DP"        android:ems= "        android:hint=" Please enter what you want to save ">        <requestfocus/>    </EditText>    <button        android:id=" @+id/btclick "        android:layout_width=" wrap_content "        android:layout_height=" wrap_content "        android:layout_ Centerhorizontal= "true"        android:layout_centervertical= "true"        android:onclick= "save"        android: text= "OK"/></relativelayout>


2. Create a new Fileservice.java class and write the save and read methods.

Fileservice.java page:

Package Com.example.file;import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Android.content.context;public class Fileservice {private Context context;public Fileservice (context context) { This.context=context;} /* Create file Save content */public void Save (String filename,string content) {BufferedWriter Bw=null;try {//Open file, get file output stream (Byte stream), parameter one is filename , parameter two for open mode, for private FileOutputStream fos=context.openfileoutput (Filename,context. mode_private)//outputstreamwriter convert byte streams to character stream, BufferedWriter create buffer bw=new bufferedwriter (FOS );//write contents to buffer bw.write (content);} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} Finally{try {if (bw!=null) {bw.close ();}} catch (IOException e) {e.printstacktrace ();}}} /* Open File read contents */public string read (string fileName) {string line; StrIngbuilder sb=new StringBuilder (); BufferedReader br=null;try {fileinputstream fis=context.openfileinput (fileName); Br=new BufferedReader (new InputStreamReader (FIS)); while ((Line=br.readline ())!=null) {sb.append (line);}} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} Finally{try {if (br!=null) {br.close ();}} catch (IOException e) {e.printstacktrace ();}} return sb.tostring ();}}


3. Write the Save method and read method, you can not write Mainactivity.java code, first write a Filetext.java class for unit testing, to detect the saving method and read method whether there is an error.

Filetext.java page:

Package Com.example.text;import Com.example.file.fileservice;import Android.test.androidtestcase;import Android.util.log;public class FileText extends Androidtestcase{public void Savetext () {Fileservice fileservice=new Fileservice (GetContext ()); Fileservice.save ("OUT.txt", "hello! ");} public void ReadText () {fileservice fileservice=new Fileservice (GetContext ()); String s=fileservice.read ("OUT.txt"); LOG.I ("Mainactivity", "s=" +s);}}


4. After writing the test class, start the test run, and the two methods run the same way.

5. After the test runs, if the green bar appears in the upper-left corner, the method is written without errors.
6. Finally write the Mainactivity.java page, which binds the save and read methods and controls. Mainactivity.java page:
Package Com.example.file;import Android.os.bundle;import Android.app.activity;import android.view.view;import Android.widget.edittext;import Android.widget.toast;public class Mainactivity extends Activity {private EditText etinput; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);/* Get Control Method */getid ();/* Read file Content method */read ();} /* Read file content method */private void Read () {Fileservice fileservice=new fileservice (this); String content=fileservice.read ("MyFile.txt"), if (!content.isempty ()) {etinput.settext (content); Etinput.setselection (Content.length ()); Toast.maketext (This, "Restoring succeeded", Toast.length_short). Show ();}} /* Click the button to invoke the Save method */public void Save (View view) {Fileservice fileservice=new fileservice (this); String Content=etinput.gettext (). toString (); Fileservice.save ("MyFile.txt", content); Toast.maketext (This, "Save succeeded", Toast.length_short). Show (); /* Get control method */private void GetId () {etinput= (EditText) Findviewbyid (r.id.etinput);}}


7. After running, you can display the target effect, you can see the file save directory from the environment, or you need to view it in the simulator environment.



8. According to the method described in the previous blog post, you can save to the desktop to view the contents of the file, you can find that the OUT.txt file is stored in the test "hello! ", the MyFile.txt file is the" 123456 "entered at run time.








android-file Storage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.