Android small function Implementation of the file read and write

Source: Internet
Author: User

Create a new Android project.


A layout
Look first:


Open the Main.xml to modify the contents as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent "    ; <textview android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "@string/F Ilename "/> <edittext android:layout_width=" fill_parent "android:layout_height=" Wrap_content "Andro         Id:id= "@+id/filename"/> <textview android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:text= "@string/file_content"/> <edittext android:layout_width= "Fill_parent" android:layout _height= "Wrap_content" android:minlines= "3" android:id= "@+id/save_file_content"/> <Button android: Layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/button_save" a Ndroid:id= "@+id/button_save"/&Gt <button android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "@string/bu Tton_read "android:id=" @+id/button_read "/> <edittext android:layout_width=" Fill_parent "Android:lay out_height= "Wrap_content" android:minlines= "3" android:id= "@+id/read_file_content"/></linearlayout&gt ;

Two definition strings
Open Strings.xml Add content as follows:

<resources>    <string name= "app_name" >File</string>    <string name= "Action_settings" >Settings</string>    <string name= "filename" > file name </string>    <string name= "File_ Content > File contents </string>    <string name= "Button_save" > Save </string>    <string name= "Save _success "> Save success </string>    <string name=" Save_fail "> Save failed </string>    <string name=" Button_read "> Read </string>    <string name=" read_success "> Read success </string>    <string name= "Read_fail" > Read failure </string></resources>

Three-function implementation
Create a new class Fileservice, for the file read and write, the complete code is as follows:

public class Fileservice {public context context;       Public Fileservice (Context context) {This.context = context; /** * Save string to File * @param name File name * @param content File contents */public void Save (string name, String con Tent) throws exception{//mode_private files created, can only be accessed by the application, and the new write content will overwrite the original content fileoutputstream OS = context.ope        Nfileoutput (name, context.mode_private);        The default is saved in the/data/data/<package_name>/files directory Os.write (Content.getbytes ());    Os.close (); }/*** * Read file contents * @param name filename * @return * @throws Exception */Public String Read (string nam        E) throws exception{FileInputStream is = context.openfileinput (name);        Bytearrayoutputstream OS = new Bytearrayoutputstream ();        byte[] buf = new byte[1024];        int len = 0;        while (len = Is.read (BUF))! =-1) {Os.write (buf,0, Len);        } byte[] data = Os.tobytearray (); String ConteNT = new String (data);    return content; }}

Four Test code
Modify the Mainactivity.java code as follows:

    Public EditText Nametext;    Public EditText Savecontenttext;    Public EditText Readcontenttext;    Public Button Button_read;    public String filename;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Nametext = (EditText) This.findviewbyid (r.id.filename);        Savecontenttext = (EditText) This.findviewbyid (r.id.save_file_content);        Readcontenttext = (EditText) This.findviewbyid (r.id.read_file_content);        Button Button_save = (button) This.findviewbyid (R.id.button_save);        Button_save.setonclicklistener (New Buttonsaveclicklistener ());        Button_read = (Button) This.findviewbyid (R.id.button_read);        Button_read.setclickable (FALSE);    Button_read.setonclicklistener (New Buttonreadclicklistener ());            } Private Final class Buttonsaveclicklistener implements view.onclicklistener{public void OnClick (View v) { String Name = Nametext.gettext (). toString ();            String content = Savecontenttext.gettext (). toString ();            Fileservice service = new Fileservice (Getapplicationcontext ());                try {filename = name;                Service.save (name, content);                filename = name;                Button_read.setclickable (TRUE);            Toast.maketext (Getapplicationcontext (), r.string.save_success, Toast.length_long). Show ();                 }catch (Exception e) {toast.maketext (Getapplicationcontext (), R.string.save_fail, Toast.length_long). Show ();            E.printstacktrace (); }}} Private final class Buttonreadclicklistener implements view.onclicklistener{public void OnClick (View v)            {Fileservice service = new Fileservice (Getapplicationcontext ());                try {String content = service.read (filename);                Readcontenttext.settext (content); Toast.maketext (getapplicAtioncontext (), r.string.read_success, Toast.length_long). Show ();                 }catch (Exception e) {toast.maketext (Getapplicationcontext (), R.string.read_fail, Toast.length_long). Show ();            E.printstacktrace (); }        }    }

Run results



Android small function Implementation of the file read and write

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.