在Android中,我们可以将一些数据直接以文件的形式保存在设备中。例如:一些文本文件、PDF文件、音视频文件和图片等。Android 提供了文件读写的方法。


通过 Context.openFileInput()方法获得标准Java文件输入流(FileInputStream),通过Context.openFileOutput()方法获得标准Java文件输出流( FileOutputStream )。使用

Resources.openRawResource(R.raw.myDataFile)方法返回InputStream。


示例如下,新建一个Activity,添加两个TextView和两个Button,点击第一个Button,将TextView上的数据写到文件中,点击第二个Button,将文件中的数据写到TextView中。


MainActivity.java:

publicclassMainActivityextendsActivity{privateStringfilename="file.txt";privateTextViewmytext1,mytext2;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mytext1=(TextView)this.findViewById(R.id.text1);mytext2=(TextView)this.findViewById(R.id.text2);Buttonbutton1=(Button)this.findViewById(R.id.btn_read);Buttonbutton2=(Button)this.findViewById(R.id.btn_write);button1.setOnClickListener(newOnClickListener(){@OverridepublicvoidonClick(Viewarg0){//TODOAuto-generatedmethodstubmytext2.setText(read());}});button2.setOnClickListener(newOnClickListener(){@OverridepublicvoidonClick(Viewarg0){//TODOAuto-generatedmethodstubwrite(mytext1.getText().toString());}});}protectedStringread(){try{FileInputStreamfis=openFileInput(filename);try{byte[]buffer=newbyte[fis.available()];fis.read(buffer);returnnewString(buffer);}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}catch(FileNotFoundExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}returnnull;}protectedvoidwrite(Stringstr){try{FileOutputStreamfos=openFileOutput(filename,MODE_APPEND);try{fos.write(str.getBytes());fos.close();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}catch(FileNotFoundExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}


activity_main.xml:

<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"><TextViewandroid:id="@+id/text1"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="我是text1"/><Buttonandroid:id="@+id/btn_write"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="write"/><TextViewandroid:id="@+id/text2"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="我是text2"/><Buttonandroid:id="@+id/btn_read"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="read"/></LinearLayout>


运行结果如下:点击write将第一个TextView写入文件,点击read将数据读出到第二个TextView