自學Android筆記——檔案儲存體

來源:互聯網
上載者:User

標籤:android   資料存放區   檔案儲存體   

1.檔案儲存體簡介:

檔案儲存體是android的基本的一種資料存放區方式,它與Java中的檔案儲存體類似,都是以I/O流的形式把資料原封不動地儲存到文檔中,不同的是,android中的檔案儲存體分為內部儲存和外部儲存。


2.內部儲存:

內部儲存是指應用程式中的資料以檔案方式儲存到裝置的內部儲存空間中。預設情況下,儲存在內部儲存內的檔案是應用程式私人的,如果其他應用程式要操作本應用程式中的檔案,需要設定許可權。當使用者卸載此應用程式時,內部儲存的資料會一併清除。

內部儲存使用的是Context提供的openFileOutput()方法和openFileInput()方法,通過這兩個方法可以分別擷取FileOutputOtream對象和FileInputStream對象,具體如下:

FileOutputStream openFileOutput(String name, int mode);FileInputStream openFileInput(String name);

其中,參數name表示檔案名稱,mode表示檔案的操作方式,也就是讀寫檔案的方式,它的取值有4種,具體如下:

MODE_PRIVATE   :預設操作模式,該檔案只能被當前程式讀寫
MODE_APPEND   :模式會檢查檔案是否存在,存在就往檔案追加內容,否則就建立新檔案。
MODE_WORLD_READABLE:表示當前檔案可以被其他應用讀取
MODE_WORLD_WRITEABLE :  表示當前檔案可以被其他應用寫入


儲存資料時,使用FileOutputStream對象將資料存放區到檔案中的範例程式碼如下:

        String filename="data.txt";        String content="helloworld";        FileOutputStream fos;        try {            fos = openFileOutput(filename, MODE_PRIVATE);            fos.write(content.getBytes());            fos.close();        }catch (Exception e) {            e.printStackTrace();        }    

取出資料時,使用FileInputStream對象讀取資料的範例程式碼如下:

        String content="";        FileInputStream fis;        try{                        fis=openFileInput("data.txt");            byte[] buffer=new byte[fis.available()];            fis.read(buffer);            content=new String(buffer);        } catch(Exception e){            e.printStackTrace();        }

3.外部儲存:

外部儲存是指將檔案儲存體到一些外圍裝置上,例如SD卡或者裝置內嵌的儲存卡,屬於永久性的儲存方式。檔案儲存到外部儲存是公開的,可由使用者修改他們。

在你使用外部存放裝置的時候,你應該總是先調用Environment.getExternalStorageState()的方法來檢查外部存放裝置的可用性。


向外圍裝置(SD卡)中儲存資料的範例程式碼如下所示:

           String state= Environment.getExternalStorageState();            if(state.equals(Environment.MEDIA_MOUNTED)){                File SDPath=Environment.getExternalStorageDirectory();                File file=new File(SDPath, "data.txt");                String data="helloworld";                FileOutputStream fos;                try {                    fos=new FileOutputStream(file);                    fos.write(data.getBytes());                    fos.close();                }catch (Exception e){                    e.printStackTrace();                }            }

從外圍裝置(SD卡)中讀取資料的範例程式碼如下所示:

            String state= Environment.getExternalStorageState();            if(state.equals(Environment.MEDIA_MOUNTED)){                File SDPath=Environment.getExternalStorageDirectory();                File file=new File(SDPath, "data.txt");                FileInputStream fis;                try {                    fis=new FileInputStream(file);                    BufferedReader br=new BufferedReader(new InputStreamReader(fis));                    String data=br.readLine();                }catch (Exception e){                    e.printStackTrace();                }            }

4.案例——儲存使用者資訊1.建立程式:

activity_main:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_alignParentLeft="true"        android:textSize="20dp"        android:text="請輸入您要儲存的資訊:"/>    <EditText        android:id="@+id/et_info"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_below="@+id/textView1"        android:ems="10"/>    <Button        android:id="@+id/btn_read"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignRight="@+id/et_info"        android:layout_below="@+id/et_info"        android:text="讀取資訊"/>    <Button        android:id="@+id/btn_save"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_below="@+id/et_info"        android:text="儲存資訊"/></RelativeLayout>


2.編寫介面互動代碼:

MainActivity:

package select.itcast.cn.cunchuxinxi;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.os.Environment;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.nio.Buffer;public class MainActivity extends Activity {    private EditText et_info;    private Button btn_save;    private Button btn_read;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //擷取布局檔案中的控制項        et_info=(EditText) findViewById(R.id.et_info);        btn_save=(Button) findViewById(R.id.btn_save);        btn_read=(Button) findViewById(R.id.btn_read);        btn_save.setOnClickListener(new ButtonListener());        btn_read.setOnClickListener(new ButtonListener());    }    private class ButtonListener implements View.OnClickListener{        public void onClick(View v){            switch (v.getId()){                case R.id.btn_save:                    String saveinfo=et_info.getText().toString().trim();                    FileOutputStream fos;                    try{                        //儲存資料                        fos=openFileOutput("data.txt", Context.MODE_APPEND);                        fos.write(saveinfo.getBytes());                        fos.close();                    } catch (FileNotFoundException e) {                        e.printStackTrace();                    } catch (IOException e) {                        e.printStackTrace();                    }                    Toast.makeText(MainActivity.this, "儲存資料成功", 0).show();                    break;                case R.id.btn_read:                    String content="";                    try{                        //擷取儲存的資料                        FileInputStream fis=openFileInput("data.txt");                        byte[] buffer=new byte[fis.available()];                        fis.read(buffer);                        content=new String(buffer);                    } catch (FileNotFoundException e) {                        e.printStackTrace();                    } catch (IOException e) {                        e.printStackTrace();                    }                    Toast.makeText(MainActivity.this, "儲存的資料是:"+content,0).show();                    break;                default:                    break;            }        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

3.運行程式:


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

自學Android筆記——檔案儲存體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.