Android数据存储(二) Files

来源:互联网 发布:c语言编程面试题 编辑:程序博客网 时间:2024/05/31 05:29

      Files把需要保存的东西通过文件的形式记录下来,当需要这些数据时,通过读取这个文件来获得这些数据即可。Android采用的是Linux内核,所以在Android系统中,文件的形式与Linux中文件形式相同。

      通过FileInputStreamFileOutputStream对文件进行操作,在Android中,文件是一个应用程序私有的,一个应用程序无法读写其它应用程序的文件。

      Android中,可以在设备本身的存储设备或者外接的存储设备中创建用于保存数据的文件。同样,默认状态下,文件是不能在不同的应用程序之间共享的。用文件存储数据,可以通过openFileOutput函数打开一个文件,如果文件不存在就自动创建,通过load方法来获取文件中的数据,通过deleteFile方法可以删除一个指定的文件。

      FilesDemo.java

package com.example.android.filesdemo;

 

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Properties;

 

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.util.Log;

import android.view.KeyEvent;

import android.widget.TextView;

 

public class FilesDemo extends Activity

{

      private MIDIPlayer mMIDIPlayer = null;

      private boolean mMusic = false;

      private TextView mTextView = null;

     

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState)

    {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

       

        mTextView = (TextView)findViewById(R.id.tv01);

        mMIDIPlayer = new MIDIPlayer(this);

       

        load();

       

        if(mMusic)

        {

             mTextView.setText("当前音乐状态:开");

                 mMusic = true;

                 mMIDIPlayer.playMusic();

        }

        else

        {

             mTextView.setText("当前音乐状态:关");

        }

    }

   

    public boolean onKeyUp(int keyCode, KeyEvent event)

    {

      switch(keyCode)

      {

            case KeyEvent.KEYCODE_DPAD_UP:

            {

                  mTextView.setText("当前音乐状态:开");

                      mMusic = true;

                      mMIDIPlayer.playMusic();

            }

            break;

           

            case KeyEvent.KEYCODE_DPAD_DOWN:

            {

                  mTextView.setText("当前音乐状态:关");

                      mMusic = false;

                      mMIDIPlayer.freeMusic();

            }

            break;

      }

     

      return true;

    }

   

    public boolean onKeyDown(int keyCode, KeyEvent event)

    {

      if(keyCode == KeyEvent.KEYCODE_BACK)

      {

            save();

           

            if(mMusic)

            {

                  mMIDIPlayer.freeMusic();

            }

           

            this.finish();

           

            return true;

      }

     

      return super.onKeyDown(keyCode, event);

    }

   

    private void load()

    {

      //A Properties object is a Hashtable where the keys

      //and values must be Strings. Each property can have

      //a default Properties list which specifies the default

      //values to be used when a given key is not found in

      //this Properties instance.

      Properties properties = new Properties();

     

      FileInputStream fis = null;

     

      try

      {

            //Open a private file associated with this Context's

            //application package for reading

                 fis = this.openFileInput("music.cfg");  //如果找不到相应的文件,会抛出异常

           }

      catch (FileNotFoundException e)

      {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }

     

      try

      {

            //Loads properties from the specified InputStream.

            //The encoding is ISO-8859-1

                 properties.load(fis);

           }

      catch (IOException e)

      {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }

     

      mMusic = Boolean.valueOf(properties.get("music").toString());

    }

   

    private boolean save()

    {

      Properties properties = new Properties();

     

      //Associate the specified value with the specified key in this Hashtable

      properties.put("music", String.valueOf(mMusic));  //属性值

     

      FileOutputStream fos = null;

     

      try

      {

            //Open a private file associated with this Context's

            //application package for writing. Creates the file

            //if it doesn't already exist

                 fos = this.openFileOutput("music.cfg", Context.MODE_WORLD_WRITEABLE);

           }

      catch (FileNotFoundException e)

      {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }

     

      try

      {

            //Stores the mappings in this Properties object to out,

            //putting the specified comment at the beginning.

            //The encoding is ISO-8859-1.

                 properties.store(fos, "");  //将属性值通过输出流进行输出

           }

      catch (IOException e)

      {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

           }

     

      return true;

    }

}

 

MIDIPlayer.java

package com.example.android.filesdemo;

 

import android.content.Context;

import android.media.MediaPlayer;

 

public class MIDIPlayer

{

      private MediaPlayer mMediaPlayer = null;

      private Context mContext = null;

     

      public MIDIPlayer(Context context)

      {

           mContext = context;

      }

     

      public void playMusic()

      {

           mMediaPlayer = MediaPlayer.create(mContext, R.raw.start);

           mMediaPlayer.setLooping(true);

          

           mMediaPlayer.start();

      }

     

      public void freeMusic()

      {

           if(mMediaPlayer != null)

           {

                 mMediaPlayer.stop();

                 mMediaPlayer.release();

           }

      }

}

 

main.xml

<?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"

    >

      <TextView

           android:id="@+id/tv01"

           android:layout_width="fill_parent"

           android:layout_height="wrap_content"

           >

      </TextView>

</LinearLayout>

 

      通过Preferences存储的数据保存在shared_prefs文件夹下,如果我们使用了文件存储数据的方式,系统就会在和shared_prefs相同的目录中产生一个名为files的文件夹,它下面的文件就是我们通过Files存储数据的文件。

      如果在开发一个应用程序时,需要通过加载一个文件的内容来初始化程序,就可以在编译程序之前,在res/raw/tempFile中建立一个static文件,这样就可以在程序中通过Resources.openRawResource(R.raw.文件名)方法同样返回一个InputStream对象,直接读取文件内容。

      注:public InputStream openRawResource (int id)

Open a data stream for reading a raw resource. This can only be used with resources whose value is the name of an asset files -- that is, it can be used to open drawable, sound, and raw resources; it will fail on string and color resources.

原创粉丝点击