一 文件存储
文件存储是原封不动的存储到文件中。
数据类型:简单的文本数据、二进制数据。
存储位置:/data/data/项目包名/files/
应用场景:不知道
核心技术:
1 Context 提供了 openFileInput() 和openFileOutput() 获得流对象
2利用流进行读写,不允许指定存储位置,系统自动会找到位置。
示例:
write(String fileName, String data) 将数据存储到文件中
String read(String fileName) 从文件中读取数据
------------------------begin--------------------------
public void write(String fileName, String data)
{
FileOutputStreamout = null;
BufferedWriterwriter = null;
try
{
out = openFileOutput(fileName, Context.MODE_PRIVATE); //还有MODE_APPEND, 表示覆盖
writer = new BufferedWriter(newOutputStreamWriter(out));
writer.write(data);
}
catch(IOExceptione){e.printStackTrace();}
finally{ if(writer!=null)try{writer.close();}catch(IOExceptione){e.printStackTrace();}}
}
public String read(String fileName)
{
FileInputStreamin = null;
BufferedReaderreader = null;
StringBuildertempSb = new StringBuilder();
try
{
in = openFileInput(fileName);
reader = new BufferedReader (new InputStreamReader(in));
Stringline = “”;
while((line = reader.readLine()) != null )
{
tempSb.append(line);
}
}
catch(IOExceptione){e.printStackTrace();}
finally{ if(reader!=null)try{reader.close();}catch(IOExceptione){e.printStackTrace();}}
returntempSb.toString();
}
------------------------end----------------------------
要去查看是否存储成功,可以在视图DDMS的File Explore,找到文件,点击向左箭头的按钮,导出到电脑,用记事本打开查看。
要用代码得到存储路径,可以使用如下方式:
String file_path = getFilesDir().getPath(); // file_path=/data/data/项目包名/files
String cache_path = getCacheDir().getPath(); // cache_path=/data/data/项目包名/cache
本文参考《第一行代码》