【Android】14.1 内部文件存储和读取

分类:C#、Android、VS2015;

创建日期:2016-02-27

一、简介

内部存储(Internal storage)是指将应用程序建立的私有文件保存在内部存储器(移动经销商卖的那种容量较小的手机卡)中。其特征如下:

  • 总是可用的
  • 文件默认只能被自己的app所访问。
  • 当用户卸载app的时候,系统会把internal内该app相关的文件都清除。
  • Internal storage是确保不被用户与其他app所访问的最佳存储区域。

可通过OpenFileInput方法和OpenFileOutput方法读取内部存储设备上的这些文件。

1、私有目录的存储位置

     /data/data/[packagename]/files:文件目录,一般保存容量较小的文件,如果是图片,不建议保存这里。

     /data/data/[packagename]/cache:缓存目录。

     /data/data/[packagename]/databases,存放数据库。

     /data/data/[packagename]/shared_prefs 保存应用的SharedPreferences。

     /data/data/[packagename]/lib,应用程序使用的.so文件目录。

2、OpenFileOutput方法

该方法打开应用程序私有文件,为写入设备做准备。默认情况下,写入的文件会覆盖同名的原文件。如果要打开的文件不存在,则创建一个新文件。

该方法的语法格式如下:

public override Stream OpenFileOutput(string name, FileCreationMode mode)

通过mode参数可更改文件写入的方式:

  • FileCreationMode.Private:私有模式(默认)。文件只能被创建的程序访问,或被具有相同UID的程序访问。
  • FileCreationMode.Append:追加模式,文件不存在就先创建再添加,存在就在原文件的末尾添加新数据。
  • FileCreationMode.WorldReadable:全局读模式,允许任何程序读取私有文件。
  • FileCreationMode.WorldWriteable:全局写模式,允许任何程序写入私有文件。

例如:

    string fileName="a1.txt";

    var f=OpenFileOutput(fileName, FileCreationMode.Private);

   string text="some data";

    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);

    f.Write(bytes, 0, bytes.Length);

    f.Flush ();

    f.Close();

注意:出于性能考虑,Android会把写入的数据先暂存到数据缓冲区中,等积累到一定程度再写入文件,因此,调用Close方法之前,一定要调用Flush方法,以确保将缓冲区的数据写入文件。

另外,为了避免忘记关闭Stream引起内存溢出,最好像本节下面的完整例子那样用using语句将其包围起来。

3、OpenFileInput方法

该方法打开应用程序私有文件,为读取做准备。该方法的语法格式如下:

public override Stream OpenFileInput(string name)

注意:name是指不带路径的文件名。

不论是读文件还是写文件,都有可能产生异常,实际使用时,始终不要忘了用try/catch捕获这些异常。作为例子,为了避免冲淡关注的内容,就不再捕获这些异常了。

4、System.IO.File类提供的静态方法

除了上面两种方式外,还可以直接用.NET提供的System.IO.File类的静态方法来读取和写入内部存储文件,而且用起来更简单。

二、示例

1、运行截图

image  image

2、设计步骤

(1)添加ch1401_Main.axml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/btnWrite"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="写私有文件到内部存储器" />
    <Button
        android:id="@+id/btnRead"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="读取内部存储器中的私有文件" />
    <TextView
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="match_parent"
        android:id="@+id/textView1"
        android:layout_marginTop="80dp"
        android:background="@android:color/holo_green_dark"
        android:gravity="fill_vertical"
        android:shadowRadius="30"
        android:textColor="@android:color/white"
        android:layout_marginLeft="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="40dp"
        android:layout_height="match_parent" />
</LinearLayout>

(2)添加ch1401MainActivity.cs文件

using System.IO;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;

namespace MyDemos.SrcDemos
{
    [Activity(Label = "【例14-1】内部文件存取")]
    public class ch1401MainActivity : Activity
    {
        private Stream stream;
        private string fileName = "a1.txt";

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.ch1401_Main);

            stream = OpenFileOutput(fileName, FileCreationMode.Private);
            string filePath = GetFileStreamPath(fileName).Path;

            var textView1 = FindViewById<TextView>(Resource.Id.textView1);
            Button btnWrite = FindViewById<Button>(Resource.Id.btnWrite);
            btnWrite.Click += delegate
            {
                //用法1--不使用Android提供的API
                string str = "Hello, 你好。";
                File.WriteAllText(filePath, str, Encoding.UTF8);
                textView1.Text = $"文件已写入内存卡。\n写入内容:{str}\n文件位置:\n{filePath}";

                //用法2--使用Android提供的API
                //using (var f = OpenFileOutput(fileName, FileCreationMode.Private))
                //{
                //    string str = "Hello, 你好。";
                //    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
                //    f.Write(bytes, 0, bytes.Length);
                //    f.Flush();
                //    filePath = GetFileStreamPath(fileName).Path;
                //    textView1.Text = $"文件已写入内存卡。\n写入内容:{str}\n文件位置:\n{filePath}";
                //}
            };

            Button btnRead = FindViewById<Button>(Resource.Id.btnRead);
            btnRead.Click += delegate
            {
                //用法1
                string s = File.ReadAllText(filePath, Encoding.UTF8);
                textView1.Text = $"读取的文件:\n{filePath}\n读出的内容:\n{s}";

                //用法2
                //using (var f = OpenFileInput(fileName))
                //{
                //    string s = "";
                //    byte[] bytes = new byte[1024];
                //    int n;
                //    while ((n = f.Read(bytes, 0, 1024)) > 0)
                //    {
                //      s += System.Text.Encoding.UTF8.GetString(bytes, 0, n);
                //    }
                //    textView1.Text = $"读取的文件:\n{filePath}\n读出的内容:\n{s}";
                //}
            };
        }
    }
}
posted @ 2016-02-27 21:54  rainmj  阅读(1103)  评论(0编辑  收藏  举报