Android学习笔记--文件存储数据

来源:互联网 发布:淘宝水果模特 编辑:程序博客网 时间:2024/05/16 10:32

将数据存储到文件中
Context 提供了一个openFileOutput()方法

  /**     * Open a private file associated with this Context's application package     * for writing.  Creates the file if it doesn't already exist.     *     * <p>No permissions are required to invoke this method, since it uses internal     * storage.     *     * @param name The name of the file to open; can not contain path     *             separators.     * @param mode Operating mode.  Use 0 or {@link #MODE_PRIVATE} for the     * default operation, {@link #MODE_APPEND} to append to an existing file,     * {@link #MODE_WORLD_READABLE} and {@link #MODE_WORLD_WRITEABLE} to control     * permissions.     *     * @return The resulting {@link FileOutputStream}.     *     * @see #MODE_APPEND     * @see #MODE_PRIVATE     * @see #MODE_WORLD_READABLE     * @see #MODE_WORLD_WRITEABLE     * @see #openFileInput     * @see #fileList     * @see #deleteFile     * @see java.io.FileOutputStream#FileOutputStream(String)     */    public abstract FileOutputStream openFileOutput(String name, int mode)        throws FileNotFoundException;

第一个参数是文件名,不包含文件的地址.
第二个参数是文件的操作模式.
MODE_APPEND 则表示如果该文件已存在就往文件里面追加内容,不存在就创建新文件.
MODE_PRIVATE 是默认的操作模式,表示当指定同样文件名的时候,所写入的内容将会覆盖原文件中的内容
MODE_WORLD_READABLE及MODE_WORLD_WRITEABLE 因为有安全漏洞Android4.2版本废弃

openFileOutput()方法返回FileOutputStream对象

FileOutputStream out =  openFileOutput("data", Context.MODE_PRIVATE);BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

从文件中读取数据
Context提供了一个openFileInput()方法

  /**     * Open a private file associated with this Context's application package     * for reading.     *     * @param name The name of the file to open; can not contain path     *             separators.     *     * @return The resulting {@link FileInputStream}.     *     * @see #openFileOutput     * @see #fileList     * @see #deleteFile     * @see java.io.FileInputStream#FileInputStream(String)     */    public abstract FileInputStream openFileInput(String name)        throws FileNotFoundException;

第一个参数是文件名

StringBuilder content = new StringBuilder();FileInputStream in = openFileInput("data");BufferedReader reader = new BufferedReader(new InputStreamReader(in));
0 0
原创粉丝点击