Android写入/读出文件demo

这篇博客介绍了如何在Android中使用Context的openFileOutput()和openFileInput()方法进行文件的读写操作。文章详细讲解了这两个方法的参数含义,特别是文件名和操作模式的设置,如MODE_PRIVATE用于覆盖写入,而MODE_APPEND则用于追加内容。通过给出的demo,读者可以了解具体的实现步骤。

    demo之前先做一下说明:

    Context类中提供的openFileOutput()方法,可以讲述数据存储到指定文件中。该方法共接收两个参数,第一个为文件名,注意这里指定的文件名不可以包含路径,因为所有的文件都是默认存储到/data/data/<packagename>/files/目录下的。第二个参数时文件的操作模式,主要有两个模式。第一个模式为MODE_PRIVATE,表示文件名重名的时候,所写入的内容会覆盖源文件的内容。第二个模式为MODE_APPEND,表示文件名已存在的时候,就往文件里追加加内容。

    Context类中提供的openFileIntput()方法,用于从文件中读取数据,只接受文件名这一个参数。

demo如下:

public void save(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 (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值