The SD card of the phone is written and read to the side of the data

Source: Internet
Author: User
Tags readfile

What we want to achieve is: enter data into the input box, click on a Write button, the input box to write the data into the SD card, the click on the Read button, the SD card is only the name of the files in the file displayed on a textview.

First, look at the XML file, very simple, only two buttons, an input box, and a text control;

Saved data can be viewed under mnt/sdcard/.

<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 "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "> <edittext android:id=" @+id/edittext1 "android:layout_width=" Wrap_content "an droid:layout_height= "Wrap_content" android:layout_alignparenttop= "true" Android:layout_centerhorizontal= "Tru    E "android:layout_margintop=" 59DP "android:ems=" > <requestfocus/> </EditText> <button android:id= "@+id/button1" android:layout_width= "wrap_content" android:layout_height= "WR Ap_content "android:layout_alignleft=" @+id/edItText1 "android:layout_below=" @+id/edittext1 "android:layout_margintop=" 46DP "android:text=" Write "/&gt    ; <button android:id= "@+id/button2" android:layout_width= "wrap_content" android:layout_height= "Wrap_ Content "Android:layout_alignbaseline=" @+id/button1 "android:layout_alignbottom=" @+id/button1 "Androi        d:layout_alignright= "@+id/edittext1" android:text= "read"/> <textview android:id= "@+id/textView1" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_above= "@+id/butt On2 "android:layout_marginbottom=" 14DP "android:layout_torightof=" @+id/button1 "android:text=" TextVie W "/></relativelayout>

The

is then a newly created feature class Fileservice, which is primarily responsible for reading and writing data to the SD card.

Package Com.example.sdcord;import Java.io.bytearrayoutputstream;import Java.io.file;import Java.io.FileInputStream ; Import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Android.content.context;import android.os.environment;/** * Mainly used to read and write data to SD card * * @author Administrator * */public class Fileservice {Private Context Context;public Fileservice (context context) {This.context = context;} /** * Write Data * * @param fileName * File name * @param context * File contents * @return The return value is false then write data fails, otherwise successful */PU Blic boolean SaveFile (String fileName, String context) {Boolean flag = false; FileOutputStream FileOutputStream = null;//getexternalstoragedirectory (): Returns the directory of the extended memory card File File = new file ( Environment.getexternalstoragedirectory (), fileName),//Getexternalstoragestate (): Returns the current state of the extended memory card, calling this method, will// Returns a string that indicates the current SD card can operate if the returned state is the same as the value of environment.media_mounted (already mounted and has a readable writable permission)//(Environment.media_ Mounted.equals (Environment.getexternalstoraGestate ())) {try {fileoutputstream = new FileOutputStream (file); Fileoutputstream.write (Context.getbytes ()); flag = true;} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {if ( FileOutputStream! = null) {}try {fileoutputstream.close ();} catch (IOException e) {e.printstacktrace ();}}} return flag;} /** * * @param filename name * @return Return the readings to the string form */public string GetFile (string filename) {FileInputStream Fileinpu TStream = null;//Buffered stream, independent of disk, so do not need to turn off bytearrayoutputstream output = new Bytearrayoutputstream (); File File = new file (Environment.getexternalstoragedirectory (), fileName);//Determine if the SD card is available if (Environment.media_ Mounted.equals (Environment.getexternalstoragestate ())) {try {FileInputStream = new FileInputStream (file); int len = 0; byte[] data = new Byte[1024];while (len = fileinputstream.read (data))! =-1) {output.write (data, 0, Len);}} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {if (FileInputStream! = null) {try {fileinputstream.close ()} catch (IOException e) {e.printstacktrace ()}}}} return new String (Output.tobytearray ());}}

Then the activity class,

1  PackageCom.example.sdcord;2 3 Importandroid.app.Activity;4 ImportAndroid.os.Bundle;5 Importandroid.text.Editable;6 ImportAndroid.view.Menu;7 ImportAndroid.view.View;8 ImportAndroid.view.View.OnClickListener;9 ImportAndroid.widget.Button;Ten ImportAndroid.widget.EditText; One ImportAndroid.widget.TextView; A  -  Public classMainactivityextendsActivityImplementsonclicklistener{ -      the     PrivateButton btn1; -     PrivateButton btn2; -     PrivateTextView TextView; -     PrivateEditText EditText; +  - @Override +     protected voidonCreate (Bundle savedinstancestate) { A         Super. OnCreate (savedinstancestate); at Setcontentview (r.layout.activity_main); -          -BTN1 =(Button) Findviewbyid (r.id.button1); -BTN2 =(Button) Findviewbyid (r.id.button2); -TextView =(TextView) Findviewbyid (r.id.textview1); -EditText =(EditText) Findviewbyid (R.ID.EDITTEXT1); in          -Btn1.setonclicklistener ( This); toBtn2.setonclicklistener ( This); +          -     } the      *      Public voidOnClick (view view) { $         Switch(View.getid ()) {Panax Notoginseng          CaseR.id.button1: -String data1 =Edittext.gettext (). toString (); theSavafile ("Test.txt", data1); +              Break; A          CaseR.id.button2: theString data2 = ReadFile ("Test.txt"); + Textview.settext (data2); -              Break; $         } $     } -      -      Public voidsavafile (String dir,string data) { theFileservice Fileservice =NewFileservice ( This); - Fileservice.savefile (dir,data);Wuyi     } the      -      Publicstring ReadFile (String fileName) { WuFileservice Fileservice =NewFileservice ( This); -String data =Fileservice.getfile (fileName); About         returndata; $     } -  -  - @Override A      Public BooleanOncreateoptionsmenu (Menu menu) { +         //inflate the menu; This adds items to the action bar if it is present. the getmenuinflater (). Inflate (R.menu.main, menu); -         return true; $     } the      the}

Finally, note that because our operation involves the write and read permissions of the SD card, the appropriate authorization information is added to the manifest file

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/>

The SD card of the phone is written and read to the side of the data

Related Article

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.