Android数据存储之文件存储

2016-09-22  本文已影响83人  狮_子歌歌

文件存储

文件存储时Android中最基本的一种数据存储方式,它对存储内容不进行任何的格式化处理,所有的数据都是原封不动地保存到文件中,适合存储一些文本数据或者二进制数据。

将数据存储到文件中

首先需要得到一个附着在文件上的输出流,Context类中提供了一个openFileOutput()方法,返回的输出流用语将数据存储到指定的文件中。该方法接收两个参数:

openFileOutput()方法返回一个FileOutputStream对象,得到该对象就可以使用java流的方式将数据写入文件中。

private void save(String input) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            try{
                out = getActivity().openFileOutput("data", Context.MODE_PRIVATE);
                writer = new BufferedWriter(new OutputStreamWriter(out));
                writer.write(input);
            }
            finally {
                if(writer != null)
                    writer.close();
                if(out != null)
                    out.close();
            }
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

从文件中读取数据

类似的我们需要先得到一个附着在文件上的输入流,Context类中提供了一个openFileInput()方法,返回的输入流可以从文件中读取数据。该方法只接收一个参数:

得到了FileInputStream对象后,就可以使用java流的方式从文件中读取数据。

private String load() {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuffer content = new StringBuffer();
        try{
            try{
                in = getActivity().openFileInput("data");
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while((line = reader.readLine()) != null)
                    content.append(line + "\n");
            }finally {
                if(reader != null)
                    reader.close();
                if(in != null)
                    in.close();
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }

实践

File存储.png
上一篇 下一篇

猜你喜欢

热点阅读