mono for android之文件系统与应用程序首选项(转)

时间:2021-04-26 19:19:38

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;
                 });
            }
        }