文件存储

将数据储存到文件中

private void save() {
        String data = "内容";
        //磁盘文件的输入流对象
        FileOutputStream out = null;
        //将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。
        BufferedWriter writer = null;
        try {
            //通过openFileOutput方法得到一个输出流,方法参数为创建的文件名(不能有斜杠)和操作模式。
            out = openFileOutput("fileName", Context.MODE_APPEND);
            //创建了一个字符写入流的缓冲区对象,并和指定要被缓冲的流对象相关联。
            writer = new BufferedWriter(new OutputStreamWriter(out));
            //写入缓冲区中
            writer.write(data);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    //关闭缓冲区,同时关闭了fw流对象  
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

将数据从文件中取出

private String getData() {
        //FileInputStream 用于读取本地文件中的字节数据,继承自InputStream类
        FileInputStream in = null;
        //BufferedReader 由Reader类扩展而来,提供通用的缓冲方式文本读取,读取一个文本行,从字符输入流中读取文本,缓冲各个字符。
        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 (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }

你可能感兴趣的:(文件存储)