数据的持久化技术(一)文件存储

    xiaoxiao2021-03-25  126

    文件存储是Android中最基本的一种存储形式,它不对存储的内容做处理,所有数据都是原封不动的保存到文档中,比较适用于一些简单的文本存储或二进制数据。

    存储

    Content类提供了openFileOutput()方法,可以将数据存储到指定的文件中。这个方法接收两个参数:

    文件名 文件是默认存放在 /data/data/<packagename>/file/ 目录下的

    文件的操作模式 主要有两种操作模式:MODE_PRIVATE 覆盖原文件内容; MODEAPPEND在原文件中追加内容

    FileOutputStream out = null; BufferedWriter writer = null; try { //存储的文件名为data,操作模式为覆盖原文件 out = openFileOutput("data", MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputText); } catch (IOException e) { e.printStackTrace(); } finally { if(writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }

    读取文件

    同样的,Content类也提供了一个 openFileInput的方法来读取数据,只接收一个参数,就是文件名,它会自动到/data/data/<packagename>/file/目录下读取数据,并返回一个FileInputStream对象,然后通过Java的IO流将数据读取出来。

    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(); } } }

    参考《第一行代码》

    转载请注明原文地址: https://ju.6miu.com/read-14863.html

    最新回复(0)