Android基础 文件存储和读取

来源:互联网 发布:淘宝省钱软件叫什么 编辑:程序博客网 时间:2024/06/06 08:34

          Android的文件存储操作与Java对文件实现I/O流的操作基本相似。

          文件存储方式分为两种:内部存储和外部存储(SD)

         1.内部存储文件路径是:/data/data/包名/,

           2.外部存储路径为/mnt/sdcard/

        

  一、内部存储文件步骤:

1.通过Context.openFileOutput方法打开文件,返回FileOutputStream

2.调用FileOutputStream.write()方法写入数据。

3.调用FileOutputStream.close()方法关闭输出流。

 

 

例题:我们还是以登陆界面为例,实现用户名密码的存储和回显。

Xml布局文件:

<RelativeLayoutxmlns: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">

 

    <EditText

       android:id="@+id/username"

       android:layout_width="wrap_content"

       android:layout_height="44dp"

       android:layout_alignParentLeft="true"

       android:layout_alignParentRight="true"

       android:hint="请输入用户名"

        android:paddingRight="8dp"/>

 

    <EditText

       android:id="@+id/password"

       android:layout_width="wrap_content"

       android:layout_height="44dp"

       android:layout_alignLeft="@id/username"

       android:layout_alignRight="@id/username"

       android:layout_below="@id/username"

       android:hint="请输入密码"

       android:inputType="textPassword"/>

 

    <Button

       android:id="@+id/button"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:layout_alignParentRight="true"

       android:layout_below="@id/password"

       android:onClick="login"

       android:text="登录"/>

 

    <CheckBox

       android:id="@+id/checkbox"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:layout_alignLeft="@id/password"

       android:layout_below="@id/password"

       android:checked="true"

       android:text="记住密码"/>

 

</RelativeLayout>

 

Java文件:

MainActivity(用来读取布局文件和按钮的监听事件)

 

 

import java.util.Map;

import android.app.Activity;

import android.os.Bundle;

import android.text.TextUtils;

import android.view.View;

import android.widget.CheckBox;

import android.widget.EditText;

import android.widget.Toast;

 

publicclass MainActivityextends Activity {

    private EditTextet_username, et_password;

    private CheckBoxcb;

 

    @Override

    protectedvoid onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        et_username = (EditText) findViewById(R.id.username);

        et_password = (EditText)findViewById(R.id.password);

        cb = (CheckBox)findViewById(R.id.checkbox);

       

        //检查是否有保存的用户名和密码,并回显

        Map<String,String> map = FileService.getSaveUserInfo(this);

        if (map != null) {

            et_username.setText(map.get("username"));

            et_password.setText(map.get("password"));

        }

 

    }

     //设置监听事件,存储用户名和密码

    publicvoid login(View view) {

        String username =et_username.getText().toString().trim();

        String password =et_password.getText().toString().trim();

        if (TextUtils.isEmpty(username)|| TextUtils.isEmpty(password)) {

            Toast.makeText(this,"用户名和密码不能为空", Toast.LENGTH_SHORT).show();

 

        } else {

            if (cb.isChecked()) {

                boolean result = FileService.saveUserInfo(this, username,

                        password);

                if (result) {

                    Toast.makeText(this,"保存用户信息成功", 0).show();

 

                }else {

                    Toast.makeText(this,"保存用户信息失败", 0).show();

                }

            }

        }

 

    }

 

}

 

 

FileService文件(用来读取数据):

 

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStreamReader;

import java.util.HashMap;

import java.util.Map;

 

import android.content.Context;

 

publicclass FileService {

   

    //获取用户名密码的方法,注意异常的捕获方法

    publicstaticboolean saveUserInfo(Contextcontext, String username,

            String password) {

       

        //帮助我们返回一个目录/data/data/包名/files/

        //File file = newFile(context.getFilesDir(), "info.txt");

        // File file=newFile("/data/data/com.example.sdcard_test/info.txt");

       

        try {

            //FileOutputStream fos = new FileOutputStream(file);

            FileOutputStream fos=context.openFileOutput("info.txt", Context.MODE_PRIVATE);

            fos.write((username +"##" + password).getBytes());

            fos.close();

 

            returntrue;

 

        } catch (Exception e) {

            e.printStackTrace();

            System.out.println("false");

            returnfalse;

        }

 

    }

   

    //读取保存的数据

    publicstatic Map<String, String> getSaveUserInfo(Context context) {

        File file =new File(context.getFilesDir(),"info.txt");

        try {

            FileInputStream fis =new FileInputStream(file);

            BufferedReader br =new BufferedReader(new InputStreamReader(fis));

            //读取一行的数据

            String str = br.readLine();

            //将一个字符串以##为分隔符分为字符串数组

            String[] infos = str.split("##");

            Map<String, String> map =new HashMap<String,String>();

            map.put("username", infos[0]);

            map.put("password", infos[1]);

            return map;

 

        } catch (Exception e) {

            e.printStackTrace();

           

            returnnull;

        }

    }

 

}

 

 

 

 

 

 

二、外部存储文件方法与内部存储基本相同。需要在Manifest文件中写入android.permission.WRITE_EXTERNAL_STORAGE,添加写入sd卡的权限。还是以登陆为例,在FileService.java中改变一下路径就可以。

publicclass FileService {

 

 

    publicstaticboolean saveUserInfo(Contextcontext, String username,

            String password) {

 

        try {   //判断SD卡是否准备好

            if (Environment.MEDIA_MOUNTED.equals(Environment

                    .getExternalStorageState())){

                //SD卡的路径

                //File file = newFile("/sdcard/info.txt");

                File file=new File(Environment.getExternalStorageDirectory(),"info.txt");

 

                FileOutputStream fos =new FileOutputStream(file);

                fos.write((username +"##" + password).getBytes());

                fos.close();

                returntrue;

            } else {

                returnfalse;

            }

 

        } catch (Exception e) {

           

            e.printStackTrace();

            System.out.println("false");

            returnfalse;

        }

 

    }

 

 

    publicstatic Map<String, String> getSaveUserInfo(Context context) {

        //SD卡的路径

        //File file = newFile("/sdcard/info.txt");

        File file=new File(Environment.getExternalStorageDirectory(),"info.txt");

        try {

            FileInputStream fis =new FileInputStream(file);

            BufferedReader br =new BufferedReader(new InputStreamReader(fis));

           

            String str = br.readLine();

           

            String[] infos = str.split("##");

            Map<String, String> map =new HashMap<String,String>();

            map.put("username", infos[0]);

            map.put("password", infos[1]);

            return map;

 

        } catch (Exception e) {

            e.printStackTrace();

 

            returnnull;

        }

    }

 

}

 

0 0
原创粉丝点击