Android 数据存储之文件存储小记

本文深入探讨了Android中文件的读写方式,通过Context类提供的openFileInput()和openFileOutput()方法实现文件读取和写入,同时给出了具体示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

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

优快云博客地址:http://blog.youkuaiyun.com/lecepin


这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王乐平

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值