Chinaunix首页 | 论坛 | 博客
  • 博客访问: 196258
  • 博文数量: 67
  • 博客积分: 2720
  • 博客等级: 少校
  • 技术积分: 625
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-05 13:53
文章分类
文章存档

2011年(1)

2010年(43)

2009年(23)

我的朋友

分类: 嵌入式

2009-11-27 19:28:10

在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下。

数据读取

  1. public static String read(Context context, String file) {
  2. String data = "";
  3. try {
  4. FileInputStream stream = context.openFileInput(file);
  5. StringBuffer sb = new StringBuffer();
  6. int c;
  7. while ((c = stream.read()) != -1) {
  8. sb.append((char) c);
  9. }
  10. stream.close();
  11. data = sb.toString();
  12. } catch (FileNotFoundException e) {
  13. } catch (IOException e) {
  14. }
  15. return data;
  16. }

从代码上,看起来唯一的不同就是文件的打开方式了: context.openFileInput(file); Android中的文件读写具有权限控制,所以使用context(Activity的父类)来打开文件,文件在相同的Package中共享。这里的 Package的概念同Preferences中所述的Package,不同于Java中的Package。

数据写入

  1. public static void write(Context context, String file, String msg) {
  2. try {
  3. FileOutputStream stream = context.openFileOutput(file,
  4. Context.MODE_WORLD_WRITEABLE);
  5. stream.write(msg.getBytes());
  6. stream.flush();
  7. stream.close();
  8. } catch (FileNotFoundException e) {
  9. } catch (IOException e) {
  10. }
  11. }

在这里打开文件的时候,声明了文件打开的方式。

一般来说,直接使用文件可能不太好用,尤其是,我们想要存放一些琐碎的数据,那么要生成一些琐碎的文件,或者在同一文件中定义一下格式。其实也可以将其包装成Properties来使用:

  1. public static Properties load(Context context, String file) {
  2. Properties properties = new Properties();
  3. try {
  4. FileInputStream stream = context.openFileInput(file);
  5. properties.load(stream);
  6. } catch (FileNotFoundException e) {
  7. } catch (IOException e) {
  8. }
  9. return properties;
  10. }
  11. public static void store(Context context, String file, Properties properties) {
  12. try {
  13. FileOutputStream stream = context.openFileOutput(file,
  14. Context.MODE_WORLD_WRITEABLE);
  15. properties.store(stream, "");
  16. } catch (FileNotFoundException e) {
  17. } catch (IOException e) {
  18. }
  19. }
阅读(1094) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~