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. 1 web应用-http协议-web框架

    web 应用 Web 应用程序是一种可以通过 Web 访问的应用程序,程序的最大好处是用户很容易访问应用程序,用户只需要有浏览器即可,不需要再安装其他软件.应用程序有两种模式 C/S.B/S.C/S ...

  2. Sypder 安装和使用

    一.安装Spyder 我傻傻以为直接下载Spyder就可以用了,但我其实大错特错了.Spyder虽然提供科学计算,但是它还需要一个介于Python和其之间的框架,或者说,显示界面PyQt5.(PyQt ...

  3. thinkphp 调用wsdl接口实例化SoapClient抛出异常

    异常:Message:SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://*****?wsdl' : failed to load externa ...

  4. 网格去噪 Mesh Denoising Guided by Patch Normal Co-filtering via Kernel Low-rank Recovery

    http://staff.ustc.edu.cn/~lgliu/ 网格去噪 https://blog.csdn.net/lafengxiaoyu/article/details/73656060

  5. TSQL--如何突破PRINT的8000大限

    相信很多DBA都喜欢干的一件事就是拼SQL语句,我也不例外,但是PRINT只能打印4000的Unicode string或8000的Non-unicode string, 这个蛋疼的限制会导致过长的s ...

  6. web开发有那些牛逼东西可以用

    1.squid 缓存网页 2.Pingdom 我使用Pingdom来验证Superexpert.com网站是否总是处在正常运行状态之中.你可以通过浏览“Pingdom.com”的方式来注册Pingdo ...

  7. (zxing.net)一维码Code 128的简介、实现与解码

    一.简介 一维码Code 128:1981年推出,是一种长度可变.连续性的字母数字条码.与其他一维条码比较起来,相对较为复杂,支持的字元也相对较多,又有不同的编码方式可供交互运用,因此其应用弹性也较大 ...

  8. Unity&C# SingerMonoManager泛型单例

    管理各种管理器 ///为什么需要单例 ///单例模式核心在于对于某个单例类,在系统中同时只存在唯一一个实例,并且该实例容易被外界所访问: ///避免创建过多的对象,意味着在内存中,只存在一个实例,减少 ...

  9. 索引+sql优化

    索引的概念: 索引是提高查询速度的一种手段.索引有很多种,以下是索引树的结构 要求查询出薪资大于5000的雇员信息,只要在树中找到5000的节点,直接查询该节点右边的数据即可,左边就不用管了,这样提高 ...

  10. java学习笔记—第三方操作数据库包专门接收DataSource-dbutils (30)

    Dbutils 操作数据第三方包.依赖数据源DataSource(DBCP|C3p0). QueryRunner – 接收DataSource|Connection,查询数据删除修改操作.返回结果. ...