android studio数据的本地存储并读写
android studio数据的本地存储并读写1.写数据String string = "要写入的内容";FileOutputStream fos = null;//设计读写文件存在失败的可能下面三行最好使用try,catch的写法fos = openFileOutput("文件名", Context.MODE_PRIVATE);fos.write(string.getBytes());fos.
·
android studio数据的本地存储并读写
1.写数据
String string = "要写入的内容";
FileOutputStream fos = null;
try {
fos = openFileOutput("文件名", Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2.读数据
try{
FileInputStream fis = openFileInput("文件名");//与写入对应写入时起的文件名,这里用写入时的名字读取的就是写入时的数据
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1){
baos.write(buffer,0,len);
}
content3 = baos.toString();//将文件数据赋值给变量content,变量可在你需要且合适的地方定义
fis.close();
}catch (Exception e){
e.printStackTrace();
}
注:如在读写数据时要刷新页面可调用onCreat(null);函数而且Activity主类必须extends自Activity而不是创建时默认的bar或者com.
更多推荐
已为社区贡献1条内容
所有评论(0)