第60章、数据文件存取至储存卡(从零开始学Android)

来源:互联网 发布:最省电的软件下载 编辑:程序博客网 时间:2024/05/01 09:27

  文件存储方式是一种较常用的方法,在Android中读取/写入文件的方法,与Java中实现I/O的程序是完全一样。

 

一、设计界面

  1、布局文件

  打开activity_main.xml文件。

  输入以下代码:

<?xml version="1.0" encoding="utf-8"?><LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button        android:id="@+id/save"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="保存数据(File)" />        <Button        android:id="@+id/read"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="读取数据(File)" /></LinearLayout>


二、程序文件

  打开“src/com.genwoxue.file/MainActivity.java”文件。

  然后输入以下代码:

package com.genwoxue.file;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileNotFoundException;import java.io.PrintStream;import java.util.Scanner;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;import android.app.Activity;public class MainActivity extends Activity {private Button btnSave=null;private Button btnRead=null;private File file=null;private static final String FILENAME="data.txt";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnSave=(Button)super.findViewById(R.id.save);btnRead=(Button)super.findViewById(R.id.read);btnSave.setOnClickListener(new OnClickListener(){        public void onClick(View v)        {      PrintStream ps=null;        //判断外部存储卡是否存在        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){        Toast.makeText(getApplicationContext(), "读取失败,SD存储卡不存在!", Toast.LENGTH_LONG).show();          return;        }                //初始化File        String path=Environment.getExternalStorageDirectory().toString()        +File.separator        +"genwoxue"        +File.separator        +FILENAME;        file=new File(path);                //如果当前文件的父文件夹不存在,则创建genwoxue文件夹    if(!file.getParentFile().exists())    file.getParentFile().mkdirs();        //写文件try {ps = new PrintStream(new FileOutputStream(file));ps.println("跟我学网址:www.genwoxue.com");ps.println("电子邮件:hello@genwoxue.com");} catch (FileNotFoundException e) {e.printStackTrace();}finally{ps.close();}        }});btnRead.setOnClickListener(new OnClickListener(){public void onClick(View v)        {StringBuffer info=new StringBuffer();//判断外部存储卡是否存在        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){        Toast.makeText(getApplicationContext(), "读取失败,SD存储卡不存在!", Toast.LENGTH_LONG).show();          return;        }                //初始化File        String path=Environment.getExternalStorageDirectory().toString()        +File.separator        +"genwoxue"        +File.separator        +FILENAME;        file=new File(path);                if(!file.exists()){        Toast.makeText(getApplicationContext(), "文件不存在!", Toast.LENGTH_LONG).show();          return;        }                //读取文件内容        Scanner scan=null;        try {scan=new Scanner(new FileInputStream(file));while(scan.hasNext()){info.append(scan.next()).append("☆☆☆\n");}Toast.makeText(getApplicationContext(), info.toString(), Toast.LENGTH_LONG).show();} catch (FileNotFoundException e) {e.printStackTrace();}finally{scan.close();}        }});}}


三、配置文件

  打开“AndroidManifest.xml”文件。

  然后输入以下代码:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.genwoxue.file"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="15" />    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.genwoxue.file.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

  注意:由于要进行读写外部存储卡操作,故而需要在AndroidManifest.xml文件中添加两项权限:

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

四、运行结果

   

原创粉丝点击