1. 程式人生 > >Android基礎_資料儲存一_檔案儲存

Android基礎_資料儲存一_檔案儲存

檔案儲存在Android中最基本的一種儲存方式,它不對儲存內容進行任何格式化處理,只是將資料原封不動地儲存到檔案當中,因此它適合儲存一些簡單的檔案和二進位制內容。Context類中提供了一個openFileOutput ()方法,可以用於將資料儲存到指定的檔案中。這個方法接收兩個引數,第一個引數是檔名,在檔案建立的時候使用的就是這個名稱,注意這裡指定的檔名不可以包含路徑,因為所有的檔案都是預設儲存到/data/data/<package name>/files/目錄下的。第二個引數是檔案的操作模式,主要有兩種模式可選,MODE_PRIVATE和MODE_APPEND。

MODE_PRIVATE:是預設的操作模式,表示當指定同樣檔名的時候,所寫入的內容將會覆蓋原檔案中的內容。


MODE_APPEND:如果該檔案已存在就往檔案裡面追加內容,不存在就建立新檔案。

寫入資料簡單的例子:

openFileOutput ()方法返回的是一個FileOutputStream物件,得到了這個物件之後就可以使用Java流的方式將資料寫入到檔案中了。

public void save() {
    String data = "Data to save";
    FileOutputStream out = null;
    BufferedWriter writer = null;
    try {
        out = openFileOutput("data", Context.MODE_PRIVATE);
        writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write(data);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

讀取資料簡單的例子:

類似於將資料儲存到檔案中,Context類中還提供了一個openFileInput()方法,用於從檔案中讀取資料。這個方法要比openFileOutput()簡單一些,它只接收一個引數,即要讀取的檔名,然後系統會自動到/data/data/<package name>/files/目錄下去載入這個檔案,並返回一個FileInputStream物件,得到了這個物件之後再通過Java流的方式就可以將資料讀取出來了。

public String load() {
    FileInputStream in = null;
    BufferedReader reader = null;
    StringBuilder content = new StringBuilder();
    try {
        in = openFileInput("data");
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return content.toString();
}


放一個簡單例子,別忘了在AndroidManifest.xml檔案中新增讀寫許可權

MainActivity.java

package com.example.testfile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener{

	Button write, read;
	EditText showWrite, showRead;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initObjects();
    }
    
    private void initObjects(){
    	write = (Button) findViewById(R.id.xml_write);
    	read = (Button) findViewById(R.id.xml_read);
    	showWrite = (EditText) findViewById(R.id.xml_showWrite);
    	showRead = (EditText) findViewById(R.id.xml_showRead);
    	write.setOnClickListener(this);
    	read.setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.xml_write:
				saveData();
				break;
			case R.id.xml_read:
				readData();
				break;
			default:
				break;
		}
	}

	private void saveData(){
		FileOutputStream out = null;
		BufferedWriter write = null;
		try {
			out = openFileOutput("data", MODE_PRIVATE);
			write = new BufferedWriter(new OutputStreamWriter(out));
			write.write(showWrite.getText().toString());
			showWrite.setText("");
			if(write!=null)
				write.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void readData(){
		StringBuilder content = new StringBuilder();
		FileInputStream in = null;
		BufferedReader reader = null;
		try {
			in = openFileInput("data");
			reader = new BufferedReader(new InputStreamReader(in));
			String line = "";
			while((line=reader.readLine())!=null){
				content.append(line);
			}
			showRead.setText(content.toString());
			if(reader!=null)
				reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
如果你覺得這篇文章對你有幫助,請留言讓我知道,謝謝了