Android(安卓)数据存储之文件存储小记
16lz
2021-12-04
前言
Android操作文件的方式和JAVA I/O操作是十分类似的,在这个我小谈一下。
Android写入文件
在Android中Context
类提供了openFileOutput()
方法,用于文件写入。默认存储路径为/data/data/<package name>/files/
中。
openFileOutput原型:
public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException { return mBase.openFileOutput(name, mode);}
第二个参数mode有4个类型:
MODE_APPEND
:检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
MODE_PRIVATE
:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。
MODE_WORLD_READABLE
:表示当前文件可以被其他应用读取
MODE_WORLD_WRITEABLE
:表示当前文件可以被其他应用写入
写入例子福利:
public void write(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 (Exception e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (Exception e2) { e2.printStackTrace(); } }}
Android读取文件
同样,在Android中Context
类还提供了openFileInput()
方法,用于文件写入。
openFileInput原型:
public FileInputStream openFileInput(String name) throws FileNotFoundException { return mBase.openFileInput(name);}
参数很简单,就一个文件名。
读取例子福利:
public String load(String fileName){ FileInputStream in = null; 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 (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (Exception e2) { e2.printStackTrace(); } } } return content.toString(); }}
总结
文件读取的核心就是Context
提供的openFileInput()
和openFileOutput()
,操作起来很简单,但是不适合用于保存一些复杂的文本数据。
博客名称:王乐平博客
博客地址:http://blog.lepingde.com
CSDN博客地址:http://blog.csdn.net/lecepin
更多相关文章
- Android(安卓)ListView控件基本用法
- Android(安卓)requires compiler compliance level 5.0 or 6.0.
- Android(安卓)JNI简单实例
- Android安全问题
- Android软件安装文件夹
- Android(安卓)圆角输入框
- 【Android】保存Bitmap到SD卡
- 详细解读Android中的搜索框(四)—— Searchable配置文件
- Android(安卓)MediaRecorder录制音频