博客
关于我
Android存储之——文件存储
阅读量:94 次
发布时间:2019-02-26

本文共 6145 字,大约阅读时间需要 20 分钟。

Android应用中常需要将程序数据持久化存储,openFileOutput()方法提供了一种简单的方式来创建或打开文件进行写入操作。本文将详细讲解如何使用此方法,包括文件存储的注意事项以及读取存储内容的实现方法。

1. openFileOutput()方法的使用

1.1 方法概述

openFileOutput()方法用于在应用的默认文件目录下创建或打开文件进行写入操作。该方法的主要用途是将程序数据持久化存储,如用户输入、偏好设置等。

1.2 方法参数

  • 参数一:文件名

    文件名应为简单的文字名称,不包含路径分隔符(如"/")。系统会自动生成存储路径:data/data/
    /files/。例如,文件itcast.txt将存储在/data/data/cn.itcast.action/files/itcast.txt。

  • 参数二:操作模式

    操作模式决定文件的访问权限和写入行为。常用模式包括:

    • Context.MODE_PRIVATE(0):默认模式,文件仅供应用内部使用,写入时会覆盖现有文件。
    • Context.MODE_APPEND(32768):若文件已存在,则内容追加到末尾;若不存在,则创建新文件。
    • Context.MODE_WORLD_READABLE(1):允许其他应用读取文件。
    • Context.MODE_WORLD_WRITEABLE(2):允许其他应用写入文件。

    建议在开发中尽量使用默认模式(MODE_PRIVATE),以确保文件的安全性。若需要其他应用访问文件,则需明确指定相应的模式。

1.3 文件存储路径

文件将被存储在以下路径下:data/data/

/files/。开发者可通过Eclipse菜单“Window”-“Show View”-“Other”选择“File Explorer”视图,查看具体存储位置。

2. 保存文件的实现示例

2.1 XML布局文件

2.2 主Activity代码

package org.day13_filesave;import java.io.BufferedReader;import java.io BufferedWriter;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.view.Menu;import android.widget.EditText;public class MainActivity extends Activity {    private EditText editText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        editText = (EditText) findViewById(R.id.editText);    }    @Override    protected void onDestroy() {        super.onDestroy();        String data = editText.getText().toString();        save(data, "fileName.txt");    }    public void save(String data, String name) {        FileOutputStream fos = null;        BufferedWriter bw = null;        try {            fos = openFileOutput(name, Context.MODE_PRIVATE);            bw = new BufferedWriter(new OutputStreamWriter(fos));            bw.write(data);            bw.flush();        } catch (Exception e) {            e.printStackTrace();        } finally {            if (bw != null) {                try {                    bw.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}

3. 读取文件的实现

为了实现读取存储内容的功能,需使用openFileInput()方法,它返回FileInputStream对象,用于读取文件内容。

3.1 openFileInput()方法的使用

openFileInput()方法与openFileOutput()类似,用于打开文件进行读取操作。其参数仅文件名,系统自动生成存储路径。

3.2 读取文件内容的实现示例

public String load(String fileName) {    FileInputStream fis = null;    BufferedReader br = null;    StringBuilder content = new StringBuilder();    try {        fis = openFileInput(fileName);        br = new BufferedReader(new InputStreamReader(fis));        String line = "";        while ((line = br.readLine()) != null) {            content.append(line);        }        return content.toString();    } catch (Exception e) {        e.printStackTrace();    } finally {        if (br != null) {            try {                br.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }    return null;}

4. 实现恢复上次输入内容

在上述基础上,可以通过读取存储文件内容,将其恢复到EditText中,提升用户体验。

4.1 修改initViews方法

private void initViews() {    editText = (EditText) findViewById(R.id.editText);    String inputText = load("fileName.txt");    if (!TextUtils.isEmpty(inputText)) {        editText.setText(inputText);        editText.setSelection(inputText.length());        Toast.makeText(this, "恢复数据成功!", 0).show();    }}

4.2 完整代码

package org.day13_filesave;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io OutputStreamWriter;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.text.TextUtils;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {    private EditText editText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initViews();    }    private void initViews() {        editText = (EditText) findViewById(R.id.editText);        String inputText = load("fileName.txt");        if (!TextUtils.isEmpty(inputText)) {            editText.setText(inputText);            editText.setSelection(inputText.length());            Toast.makeText(this, "恢复数据成功!", 0).show();        }    }    @Override    protected void onDestroy() {        super.onDestroy();        String data = editText.getText().toString();        save(data, "fileName.txt");    }    public void save(String data, String name) {        FileOutputStream fos = null;        BufferedWriter bw = null;        try {            fos = openFileOutput(name, Context.MODE_PRIVATE);            bw = new BufferedWriter(new OutputStreamWriter(fos));            bw.write(data);            bw.flush();        } catch (Exception e) {            e.printStackTrace();        } finally {            if (bw != null) {                try {                    bw.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    public String load(String fileName) {        FileInputStream fis = null;        BufferedReader br = null;        StringBuilder content = new StringBuilder();        try {            fis = openFileInput(fileName);            br = new BufferedReader(new InputStreamReader(fis));            String line = "";            while ((line = br.readLine()) != null) {                content.append(line);            }            return content.toString();        } catch (Exception e) {            e.printStackTrace();        } finally {            if (br != null) {                try {                    br.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return null;    }}

5. 注意事项

  • 文件安全:默认存储路径为data/data/
    /files/,文件权限设置为私有,其他应用无法访问。
  • 文件名规范:文件名不应包含路径分隔符,避免存储时出现问题。
  • 读取与写入顺序:确保在读取文件前检查文件存在,避免NullPointer异常。

通过以上方法,开发者可以方便地在Android应用中实现文件的存储与读取,提升用户体验。

转载地址:http://nrvk.baihongyu.com/

你可能感兴趣的文章
Objective-C实现euler method欧拉法算法(附完整源码)
查看>>
Objective-C实现eulerianPath欧拉路径算法(附完整源码)
查看>>
Objective-C实现eval函数功能(附完整源码)
查看>>
Objective-C实现Exceeding words超词(差距是ascii码的距离) 算法(附完整源码)
查看>>
Objective-C实现extended euclidean algorithm扩展欧几里得算法(附完整源码)
查看>>
Objective-C实现factorial iterative阶乘迭代算法(附完整源码)
查看>>
Objective-C实现FigurateNumber垛积数算法(附完整源码)
查看>>
Objective-C实现Gale-Shapley盖尔-沙普利算法(附完整源码)
查看>>
Objective-C实现hamming numbers汉明数算法(附完整源码)
查看>>
Objective-C实现hanoiTower汉诺塔算法(附完整源码)
查看>>
Objective-C实现hardy ramanujana定理算法(附完整源码)
查看>>
Objective-C实现highest response ratio next高响应比优先调度算法(附完整源码)
查看>>
Objective-C实现hill climbing爬山法用来寻找函数的最大值算法(附完整源码)
查看>>
Objective-C实现hornerMethod霍纳法算法(附完整源码)
查看>>
Objective-C实现Http Post请求(附完整源码)
查看>>
Objective-C实现Http协议下载文件(附完整源码)
查看>>
Objective-C实现IIR 滤波器算法(附完整源码)
查看>>
Objective-C实现IIR数字滤波器(附完整源码)
查看>>
Objective-C实现insertion sort插入排序算法(附完整源码)
查看>>
Objective-C实现integer partition整数分区算法(附完整源码)
查看>>