Aside from persistent files, your application might need to store cache data in a file. To do that, you would use GetCacheDir() along with a File object to open a file in the cache directory. Cache files are subject to removal by Android if the system runs low on internal storage space, but you should not count on the system's cleaning up these files for you. If your application is removed, the cache files it owns are removed also. But, as a good Android citizen you should remove any unused cache files.
除开持久化的文件,应用程序还可以使用文件的缓存数据,使用File对象的GetCacheDir()方法可打开打开缓存目录的文件。缓存文件在系统内部存储空间低的时候会清除,但是你不能光依靠这种自动机制,要记得自己清除不用的缓存。
In addition to file creation, file placement also occurs. Files can be placed in internal or external storage. Internal storage refers to the built-in device storage, and external storage refers to a media card that can be added to the device. The two systems are accessed in a slightly different manner.
文件存放的位置,可被存放在内部存储和外部存储(外接存储卡)中。使用方式有一点点不同:
For internal files, the following functions are used:
内部存储的使用方法如下:
OpenFileInput (filename, operatingmode)
OpenFileOutput (filename, operatingmode)
For external storage the operation is different. First you must check to see if any external storage is available. If it is, you have to check to see if it is writable. After you have confirmed that external storage is available, you use GetExternalFilesDir() in conjunction with a standard File() object to create a file on the external storage medium.
外部存储的使用时要先检查外存是否存在,然后检查外存是否可写,如果可写,使用GetExternalFilesDir() 方法结合File() 对象在外存上创建文件。
if (Android.OS.Environment.ExternalStorageState == Android.OS.Environment
  .MediaMounted)
                {
                    File dataDir = this.GetExternalFilesDir(Android.OS.Environment
                      .DataDirectory.Path);
                    FileOutputStream fos = OpenFileOutput(dataDir +
                      QUICKEDIT_FILENAME, FileCreationMode.Private);
                    UTF8Encoding enc = new UTF8Encoding();
                    fos.Write(enc.GetBytes(content));
                    fos.Close();
                }
GetExternalFilesDir 方法的参数是一个路径,系统中有些默认路径,如下:
Directory Constant
Description
DirectoryAlarms
警告铃声所在目录
DirectoryDcim
相机拍照目录
DirectoryDownloads
文件下载目录
DirectoryMovies
电影目录
DirectoryMusic
音乐目录
DirectoryNotifications
提醒铃声目录
DirectoryPictures
图片目录.
DirectoryPodcasts
播客文件目录
DirectoryRingtones
铃声目录
如果该函数的参数为空,则返回外存根目录。外存同样可以通过GetExternalCacheDir()获取到外部缓存所在目录。
终于到重点……读写文件了,文件可以以流的方式读写,也可以随机读写。下面是读文件的例子:
byte[] content = new byte[1024];
FileInputStream fis = OpenFileInput(QUICKEDIT_FILENAME);
fis.Read(content);
fis.Close();
写文件的例子:
String content = "content";
FileOutputStream fos = OpenFileOutput("filename.txt",
FileCreationMode.Private);
UTF8Encoding enc = new UTF8Encoding();
fos.Write(enc.GetBytes(content));
fos.Close();
 
应用程序首选项
Application preferences are simple maps of name-value pairs. Name-value pairs are stored through a key string and then one of a limited number of value types:
应用程序首选项其实就是一些键值对,键是字符串,值可以是如下类型:
Boolean
Float
Int
Long
String
The two types of preferences are private and shared. Private preferences are private to an activity within an application. Shared preferences are named and can be opened by any activity within the application. The function calls for each are as follows:
首选项分为私用和共享两种,私有选项只能由一个Activity访问,共享选项可由程序中任意Activity访问。访问两种选项的方法如下:
GetPreferences(mode)
GetSharedPreferences(name, mode)
第一个函数其实就是将第二个函数包了一下,内部指定了要访问的Activity。mode参数与前面讲的文件访问模式意义一样,只是这里只有三种访问模式,如下:
FileCreationMode.Private
FileCreationMode.WorldReadable
FileCreationMode.WorldWriteable
访问首选项的例子如下,需要注意的是两种方法返回的都是ISharedPreferences 。
ISharedPreferences p = GetPreferences(FileCreationMode.Private);
String value = p.GetString("MyTextValue", "");
通过键获得值的方法如下:
GetString
GetFloat
GetInt
GetLong
GetBoolean
GetAll
  You access this interface through a call to p.Edit() on the ISharedPreferences object. The following code snippet shows getting, editing, and storing the edited values:
使用SharedPreferences.Editor接口可以编辑首选项,例子如下:
ISharedPreferences p = GetPreferences(FileCreationMode.Private);
String value = p.GetString("MyTextValue", "");
value = "New Value";
ISharedPreferencesEditor e = p.Edit();
e.PutString("MyTextValue",value);
e.Commit();
有五个接口可以编辑首选项:
PutString(string key, string value)
PutInt(string key, int value)
PutLong(string key, long value)
PutFloat(string key, float value)
PutBoolean(string key, boolean value)
两个移除首选项的接口:
Remove(string key) //按键移除
Clear()  //全部移除
一个同步接口用来保存更改:
Boolean Commit();
假定首选项都保存到一个文件里了,然后从界面上展示这些选项,并且需要用户能够修改,修改完毕能保持到文件里。该怎么做呢?有两个重要的方法来注册和注销对文件的监视。
RegisterOnSharedPreferenceChangeListener (ISharedPreferencesOnSharedPreferenceChangeListener)
UnregisterOnSharedPreferenceChangeListener (ISharedPreferencesOnSharedPreferenceChangeListener)
使用实例如下:
protected override void OnResume()
{
    base.OnResume();
    this.GetPreferences(FileCreationMode.Private)
      .RegisterOnSharedPreferenceChangeListener(this);
}
protected override void OnPause()
{
    base.OnPause();
    this.GetPreferences(FileCreationMode.Private)
      .UnregisterOnSharedPreferenceChangeListener(this);
}
public void OnSharedPreferenceChanged(ISharedPreferences prefs, string key)
{
    // Do something with the changed value pointed to by key
}
 
XML解析类:
the DOM parser, the SAX parser, and an XML pull parser.同样也可以使用C#的Linq XML 来解析访问XML文件。
使用示例如下,此例演示了下载一个xml并将xml中内容读入一个list中:
private void getFreshMeatFeed()
{
            WebClient client = new WebClient();
            client.DownloadStringAsync(new
            Uri("http://freshmeat.net/?format=atom"));
            client.DownloadStringCompleted += new
            DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
}
private void client_DownloadStringCompleted(object sender,
    DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                XDocument xml = XDocument.Parse(e.Result);
                XNamespace atomNS = "http://www.w3.org/2005/Atom";
                System.Collections.Generic.IEnumerable<AtomEntry> list = (from
                    entry in xml.Descendants(atomNS + "entry")
                 select new AtomEntry()
                 {
                     ID = entry.Element(atomNS + "id").Value,
                     Title = entry.Element(atomNS + "title").Value,
                     Content = entry.Element(atomNS + "content").Value,
                     Published = DateTime.Parse(entry.Element(atomNS +
                         "published").Value),
                     Updated = DateTime.Parse(entry.Element(atomNS +
                         "updated").Value)
                 });
                 ArrayList titles = new ArrayList();
                 foreach (AtomEntry atomEntry in list) {
                     titles.Add(atomEntry.Title);
                 }
                 this.RunOnUiThread(() =>
                 {
                     Java.Lang.Object[] test = list.ToArray();
                     ArrayAdapter aao = new ArrayAdapter<Java.Lang.Object>(this,
    Android.Resource.Layout.SimpleListItem1,test);
                  ((ListView)this.FindViewById(Resource.Id.FMListView)).Adapter
    = aao;
                 });
            }
        }

mono for android之文件系统与应用程序首选项(转)的更多相关文章

  1. Xamarin android PreferenceActivity 实现应用程序首选项设置(一)

    应用程序首选项屏幕 类似系统设置界面. PreferenceActivity 是另一种类型的Activity,通过PreferenceActivity 可以以最少量的工作显示某些Preference列 ...

  2. Xamarin.Android学习之应用程序首选项

    Xamarin.Android学习之应用程序首选项 一.前言 任何App都会存在设置界面,如果开发者利用普通控件并绑定监听事件保存设置,这一过程会非常的枯燥,而且耗时.我们可以看到Android系统的 ...

  3. 应用程序首选项(application preference)及数据存储

    应用程序首选项(application preference)用来存储用户设置,考虑以下案例: a. 假设有一款MP3播放器程序,当用户调节了音量,当下次运行该程序时,可能希望保持上一次调节的音量值. ...

  4. Android(4)—Mono For Android 第一个App应用程序

    0.前言 年前就计划着写这篇博客,总结一下自己做的第一个App,却一直被新项目所累,今天抽空把它写完,记录并回顾一下相关知识点,也为刚学习Mono的同学提供佐证->C#也是开发Android的! ...

  5. mono for android 用ISharedPreferences 进行状态保持 会话保持 应用程序首选项保存

    由于项目需要 要保持用户登录状态 要进行状态保持 用途就好像asp.net的session一样 登录的时候进行保存 ISharedPreferences shared = GetSharedPrefe ...

  6. 我的第一个 Mono for Android 应用

    创建 Mono for Android 应用 打开 MonoDevelop , 选择新建解决方案, 左边的分类选择 "Mono for Android" , 右边选择 " ...

  7. 我的Android 4 学习系列之文件、保存状态和首选项

    目录 使用Shared Preference 保留简单的应用程序数据 保存回话间的Activity实例数据 管理应用程序首选项和创建Preference Screen 保存并加载文件以及管理本地文件系 ...

  8. 详解Android首选项框架ListPreference

    详解Android首选项框架ListPreference 原文地址 探索首选项框架 在深入探讨Android的首选项框架之前,首先构想一个需要使用首选项的场景,然后分析如何实现这一场景.假设你正在编写 ...

  9. 转:Android preference首选项框架

    详解Android首选项框架ListPreference 探索首选项框架 在 深入探讨Android的首选项框架之前,首先构想一个需要使用首选项的场景,然后分析如何实现这一场景.假设你正在编写一个应用 ...

随机推荐

  1. 从《数据挖掘概念与技术》到《Web数据挖掘》

    从<数据挖掘概念与技术>到<Web数据挖掘> 认真读过<数据挖掘概念与技术>的第一章后,对数据挖掘有了更加深刻的了解.数据挖掘是知识发展过程的一个步骤.知识发展的过 ...

  2. word 写博客,直接上传

    目前大部分的博客作者在用Word写博客这件事情上都会遇到以下3个痛点: 1.所有博客平台关闭了文档发布接口,用户无法使用Word,Windows Live Writer等工具来发布博客.使用Word写 ...

  3. DateUtils常用方法

    一.DateUtils常用方法   1.1.常用的日期判断 isSameDay(final Date date1, final Date date2):判断两个时间是否是同一天: isSameInst ...

  4. solr特点五: MoreLikeThis(查找相似页面)

    在 Google 上尝试一个查询,您会注意到每一个结果都包含一个 “相似页面” 链接,单击该链接,就会发布另一个搜索请求,查找出与起初结果类似的文档.Solr 使用MoreLikeThisCompon ...

  5. easyui 导出 excel

    <div style="margin-bottom:5px" id="tb"> <a href="#" class=&qu ...

  6. stack和stack frame

    首先,我们先来了解下栈帧和栈的基本知识: 栈帧也常被称为“活动记录”(activation record),是编译器用来实现过程/函数调用的一种数据结构. 从逻辑上讲,栈帧就是一个函数执行的环境,包含 ...

  7. 【总结】 NOIp2018考时经历记

    可能我因为比较菜的原因,还是要写一下这个东西! 发布时间迟与更新时间,毕竟浙江选手为先例 那么希望NOIp8102RP++!!! 突然发现博客园支持更新创作时间了,那么就不咕了! 本次NOIp感受很深 ...

  8. 学习笔记|JSP教程|菜鸟教程

    学习笔记|JSP教程|菜鸟教程 ------------------------------------------------------------------------------------ ...

  9. linuxea:ELK5.5-elasticsearch-x-pack破解

    本站采用知识共享署名-非商业性使用-相同方式共享国际许可协议4.0 进行许可 本文作者:www.linuxea.com for Mark 文章链接:https://www.linuxea.com/17 ...

  10. Linux下配置环境变量的几个方法实例

    场景:一般来说,配置交叉编译工具链的时候需要指定编译工具的路径,此时就需要设置环境变量.例如我的mips-linux-gcc编译器在“/opt/au1200_rm/build_tools/bin”目录 ...