Android數據存儲之內部文件存儲(一)

我們可以直接保存一個文件到內部設備的存儲,這個文件默認的保存在內部存儲的應用是私有的,其他應用是永遠訪問不到的。當用戶卸載這個app應用的時候,這些文件都會被卸載掉。

文件以.txt的格式被保存

保證程序運行的效率,第一次取下來的圖片,我們把它保存在本地,下次再運行同樣的界面就不需要在網絡上取圖片了,只需要在本地把圖片提取出來,這樣就實現了緩存的操作(這種叫硬件緩存)。主要是使用手機的存儲能力作爲緩存。

創建一個私有的內部文件步驟:

①調用openFileOutput()

②往文件裏面寫用write()

③close()

創建工程Android_data_InteralStorage,添加單元測試

在AndroidManifest.xml中單擊Instrumentation->Add->雙擊Instrumentation->Name Browse 選中android.test.InstrumentationTestRunner->Target Packet Browse 選中自己的工程名的包->點擊AndroidManifest,在application節點裏面添加 <uses-library android:name="android.test.runner"/>

創建包com.example.android_data_interalstorage.file中新建一個類FileSave.java

package com.example.android_data_interalstorage.file;

import java.io.FileOutputStream;

import android.content.Context;

public class FileSave {
	private Context context;
	
	public FileSave() {
		// TODO Auto-generated constructor stub
		this.context=context;
	}
	
	/**
	 * 
	 * @param fileName
	 * @param mode
	 * @param data
	 * @return
	 */
	public boolean saveContentToFile(String fileName,int mode, byte[] data){
		boolean flag=true;
		FileOutputStream outputStream = null;
		try {
			outputStream = context.openFileOutput(fileName, mode);
			outputStream.write(data, 0, data.length);
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
		}
		return flag;
	}
	
}

在com.example.android_data_interalstorage下創建單元測試MyTest.java

package com.example.android_data_interalstorage;

import com.example.android_data_interalstorage.file.FileSave;

import android.content.Context;
import android.test.AndroidTestCase;
import android.util.Log;

public class MyTest extends AndroidTestCase {
	private final String TAG = "MyTest";

	public void save() {
		FileSave fileSave = new FileSave(getContext());
		//操作文件的模式:private 私有模式 追加 append
		//MODE_WORLD_READABLE 可讀
		//MODE_WORLD_WRITEABLE 可寫
		//文件必須加後綴名aa.txt,xml的不需要加後綴名
		boolean flag = fileSave.saveContentToFile("aa.txt",
				Context.MODE_PRIVATE, "第一次創建".getBytes());
		Log.i(TAG, "--->>" + flag);
	}
	
}
雙擊save()進行單元測試


做個小例子:做一個界面,點擊保存信息,把編輯框的數據保存在文件裏(.txt)

在activity_main.xml中添加代碼

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="18dp"
        android:ems="10" >

    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp"
        android:text="保存信息" />

在MainActivity.java中

package com.example.android_data_interalstorage;

import com.example.android_data_interalstorage.file.FileSave;

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	private EditText editText;
	private Button button;
	private FileSave fileSave=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		fileSave=new FileSave(this);
		editText=(EditText) this.findViewById(R.id.editText1);
		button=(Button) this.findViewById(R.id.button1);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String value=editText.getText().toString().trim();
				boolean flag=fileSave.saveContentToFile("login.txt", Context.MODE_APPEND, value.getBytes());
				if(flag){
					Toast.makeText(MainActivity.this, "保存文件成功", 1).show();
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.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();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

運行效果(不是測試)如下

再輸入123ccnu繼續保存則在login.txt中數據

因爲是追加形式Context.MODE_APPEND,可以直接追加在文件數據後面。




接下來,讀取文件

FileSave.java中

package com.example.android_data_interalstorage.file;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.content.Context;

public class FileSave {
	private Context context;
	
	public FileSave(Context context) {
		// TODO Auto-generated constructor stub
		this.context=context;
	}
	
	/**讀文件
	 * 
	 * 一般在IO流中要有盤符路徑,但是在Android開發中沒有盤符的概念,因爲Android開發是基於linux的開發
	 * @param fileName
	 * @return
	 */
	public String readContentFromFile(String fileName) {
		FileInputStream fileInputStream = null;
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		try {
			fileInputStream = context.openFileInput(fileName);
			int len = 0;
			byte[] data = new byte[1024];
			while((len = fileInputStream.read(data))!=-1){
				outputStream.write(data, 0, len);
			}
			return new String(outputStream.toByteArray());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 
	 * @param fileName
	 * @param mode
	 * @param data
	 * @return
	 */
	public boolean saveContentToFile(String fileName,int mode, byte[] data){
		boolean flag=true;
		FileOutputStream outputStream = null;
		try {
			outputStream = context.openFileOutput(fileName, mode);
			outputStream.write(data, 0, data.length);
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
		}
		return flag;
	}
	
}

在MyTest.java中添加單元測試代碼

public void read(){
		FileSave service = new FileSave(getContext());
		String msg = service.readContentFromFile("login.txt");
		Log.i(TAG, "--->>" + msg);
	}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章