Android写入/读出文件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();
}
发布了113 篇原创文章 · 获赞 33 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_38367681/article/details/105689813