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. 2016-2017-2 20155223 实验二 《Java面向对象程序设计》

    2016-2017-2 苏黄永郦 实验二 实验报告 前期准备工作--程序安装 -问题一 开始的时候我就在老师博客的指导下安装IDEA插件JUnit Generator V2.0.当然我的IDEA肯定没 ...

  2. 组队作业_One

    Part 1.前言 结对项目作业 结对同学高裕翔的博客 本博文pdf版本 Part 2.PSP表 PSP3.1 Personal Software Process Stages 预估耗时(分钟) 实际 ...

  3. 23 DesignPatterns学习笔记:C++语言实现 --- 1.3 Singletion

    23 DesignPatterns学习笔记:C++语言实现 --- 1.3 Singletion 2016-07-21 (www.cnblogs.com/icmzn) 模式理解  

  4. 深海划水队项目---七天冲刺day2

    上完选修后的站立式会议: 工作进度 昨天已完成的工作: 这周任务分配,每日任务要求. 今天计划完成的工作: 推进开发进度,进一步理清开发思路. 工作中遇到的困难: 站立式会议好难统一时间啊. 燃尽图 ...

  5. 使用jdbc的方式访问kylin cube的数据

    使用jdbc的方式访问kylin cube的数据 引用kylin相关的jar包 <dependency> <groupId>org.apache.kylin</group ...

  6. c# .NET RSA结合AES加密服务端和客户端请求数据

    这几天空闲时间就想研究一下加密,环境是web程序,通过js请求后台返回数据,我想做的事js在发送请求前将数据加密,服务端收到后解密,待服务端处理完请求后,将处理结果加密返回给客户端,客户端在解密,于是 ...

  7. Eclipse导出JAR过程

    Eclipse是一款免费的JAVA开发环境,被各个软件公司使用,可以说是目前使用最多的JAVA开发工具了,网址:http://www.eclipse.org 下面演示如何建立JAVA工程和导出JAR: ...

  8. “全栈2019”113篇Java基础学习资料及总结

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  9. loadrunner代理录制

    loadrunner在使用过程中会受到浏览器版本的限制,有些web服务在低版本的浏览器上不能兼容,可通过代理录制的方式解决此问题. 注: (1)本文中的ip仅作示例,要按实际测试情况填写ip. (2) ...

  10. vue 动态组件

    动态组件 多个组件通过同一个挂载点进行组件的切换,is的值是哪个组件的名称,那么页面就会显示哪个组件 内置组件 (内置组件不会被渲染到页面上) component is属性     keep-aliv ...