前言

Android操作文件的方式和JAVA I/O操作是十分类似的,在这个我小谈一下。

Android写入文件

在Android中Context类提供了openFileOutput()方法,用于文件写入。默认存储路径为/data/data/<package name>/files/中。

openFileOutput原型:

public FileOutputStream openFileOutput(String name, int mode)    throws FileNotFoundException {    return mBase.openFileOutput(name, mode);}

第二个参数mode有4个类型:

MODE_APPEND:检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入

写入例子福利:

public void write(String inputText){    FileOutputStream out = null;    BufferedWriter writer = null;    try {        out = openFileOutput("data", Context.MODE_PRIVATE);        writer = new BufferedWriter(new OutputStreamWriter(out));        writer.write(inputText);    } catch (Exception e) {        e.printStackTrace();    } finally {        try {            if (writer != null) {                writer.close();            }        } catch (Exception e2) {            e2.printStackTrace();        }    }}

Android读取文件

同样,在Android中Context类还提供了openFileInput()方法,用于文件写入。

openFileInput原型:

public FileInputStream openFileInput(String name)    throws FileNotFoundException {    return mBase.openFileInput(name);}

参数很简单,就一个文件名。

读取例子福利:

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

总结

文件读取的核心就是Context提供的openFileInput()openFileOutput(),操作起来很简单,但是不适合用于保存一些复杂的文本数据。

博客名称:王乐平博客

博客地址:http://blog.lepingde.com

CSDN博客地址:http://blog.csdn.net/lecepin



更多相关文章

  1. Android(安卓)ListView控件基本用法
  2. Android(安卓)requires compiler compliance level 5.0 or 6.0.
  3. Android(安卓)JNI简单实例
  4. Android安全问题
  5. Android软件安装文件夹
  6. Android(安卓)圆角输入框
  7. 【Android】保存Bitmap到SD卡
  8. 详细解读Android中的搜索框(四)—— Searchable配置文件
  9. Android(安卓)MediaRecorder录制音频

随机推荐

  1. (C++)错误的map删除操作和STL中容器的迭代
  2. 第一章C++:函数返回值、GNU编译器命令
  3. 案例分享c++ map的使用和 查找性能测试
  4. C++引用的意义与引用的本质
  5. 从事C/C++开发多年,给零基础想学习C/C++的
  6. C++ 布尔类型和引用的用法详解
  7. C语言不简单,连程序员都这么说,为什么呢?
  8. C#引用类型: 按值传递,按引用传递的对比
  9. C++中的四种强制类型转换_基本用法及使用
  10. 探索C++虚函数在g++中的实现(动多态)_虚函