Android数据存储:File

Android数据存储之File

Files:它通过FileInputStream和FileOuputStream对文件进行操作。但是在Android中,文件是一个应用程序私有的,一个应用程序无法读写其他应用程序的文件。
使用方法:通过 openFileOutput方法来打开一个文件(如果该文件不存在则自动创建一个文件),通过load方法来获取文件中的数据。通过save方法来存储数据通过
deleteFile方法可以删除一个指定文件。
代码如下:
读取数据:
/* 装载、读取数据 */
void load()
{
  /* 构建Properties对对象 */
  Properties properties = new Properties();
  try
  {
   /* 打开文件 */
   FileInputStream stream = this.openFileInput("music.cfg");
   /* 读取文件内容 */
   properties.load(stream);
  }
  catch (FileNotFoundException e)
  {
   return;
  }
  catch (IOException e)
  {
   return;
  }
  /* 取得数据 */
  mbMusic = Boolean.valueOf(properties.get("bmusic").toString());
}
存储数据:
/* 保存数据 */
boolean save()
{
  Properties properties = new Properties();
  /* 将数据打包成Properties */
  properties.put("bmusic", String.valueOf(mbMusic));
  try
  {
   FileOutputStream stream = this.openFileOutput("music.cfg", Context.MODE_WORLD_WRITEABLE);
   /* 将打包好的数据写入文件中 */
   properties.store(stream, "");
  }
  catch (FileNotFoundException e)
  {
   return false;
  }
  catch (IOException e)
  {
   return false;
  }
  return true;
}
如果我们使用了文件存储数据的方式,系统就会在和shared_prefs相同的目录中产生一个名为files的文件夹。

相关参考链接:

相关代码下载链接:

原文地址:https://www.cnblogs.com/klcf0220/p/3245205.html