Android學習筆記---android資料儲存與訪問
阿新 • • 發佈:2019-02-04
資料儲存與訪問
---------------------------------------
一個在手機和sd卡上儲存檔案的例子
1.a.檔名稱:lable
b.一個text框
c.檔案內容:label
d.一個text框
e.儲存:button
-----------------------------
/File/res/layout
package com.credream.file;
import com.credream.service.FileService;
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;
import android.widget.Toast;
import android.widget.SimpleAdapter.ViewBinder;
public class FileActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new ButtonClickListener());
}
private final class ButtonClickListener implements View.OnClickListener
{
@Override
public void onClick(View v)
{
EditText
filenameText = (EditText) findViewById(R.id.filename);
EditText
contentText = (EditText) findViewById(R.id.filecontent);
String filename = filenameText.getText().toString();
String content = contentText.getText().toString();
FileService service = new FileService(getApplicationContext());
// 這裡也可以傳FileActivity,因為FileActivity類,也是繼承自
// Context
try
{
service.save(filename, content);
Toast.makeText(getApplicationContext(), R.string.success, 1)
.show();
} catch (Exception e)
{
Toast.makeText(getApplicationContext(), R.string.fail, 1)
.show
();
e.printStackTrace();
}
}
}
}
-----------------------------------------
/File/src/com/credream/service/FileService.java
package com.credream.service;
import java.io.FileOutputStream;
import android.content.Context;
public class FileService
{
/**
*儲存檔案
* @param filename 檔名稱
* @param content 檔案內容
*/
private Context context;
public FileService(Context context)
{
this.context = context;
}
public void save(String filename, String content) throws Exception
{
//IO j2ee
FileOutputStream outStream=context.openFileOutput
(filename,Context.MODE_PRIVATE);
//mode:以覆蓋形式和追加形式兩種
//context.openFileOutput(filename,mode)
//Context.MODE_PRIVATE私有操作模式 創建出來的檔案只能被本應用訪問
;其他應用無法訪問該檔案
//另外採用私有操作模式建立的檔案,寫入檔案中的內容覆蓋原始檔的內容
outStream.write(content.getBytes());//content.getBytes()這個方法
呼叫系統的
//Returns a new byte array containing the characters of this
string encoded using the system's default charset.
//預設是用utf-8
//The behavior when this string cannot be represented in the
system's default charset is unspecified. In practice, when the default charset is
UTF-8 (as it is on Android), all strings can be encoded.
//沒有預設編碼的時候,會用iso8859-1來編碼
}
}
----------------------------------------------------------------
openFileOutput()方法的第一引數用於指定檔名稱,不能包含路徑分隔符“/” ,如果文
件不存在,Android 會自動建立它。建立的檔案儲存在/data/data/<package name>/files目
錄,如: /data/data/cn.itcast.action/files/itcast.txt ,通過點選Eclipse菜
單“Window”-“Show View”-“Other”,在對話視窗中展開android資料夾,選擇下面的
File Explorer檢視,然後在File Explorer檢視中展開/data/data/<package name>/files目
錄就可以看到該檔案。
openFileOutput()方法的第二引數用於指定操作模式,有四種模式,分別為:
Context.MODE_PRIVATE = 0
Context.MODE_APPEND = 32768
Context.MODE_WORLD_READABLE = 1
Context.MODE_WORLD_WRITEABLE = 2
Context.MODE_PRIVATE:為預設操作模式,代表該檔案是私有資料,只能被應用本身訪問,
在該模式下,寫入的內容會覆蓋原檔案的內容,如果想把新寫入的內容追加到原檔案中。可
以使用Context.MODE_APPEND
Context.MODE_APPEND:模式會檢查檔案是否存在,存在就往檔案追加內容,否則就建立新文
件。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其他應用是否有權
限讀寫該檔案。
MODE_WORLD_READABLE:表示當前檔案可以被其他應用讀取;MODE_WORLD_WRITEABLE:表示當
前檔案可以被其他應用寫入。
如果希望檔案被其他應用讀和寫,可以傳入:
openFileOutput("itcast.txt", Context.MODE_WORLD_READABLE +
Context.MODE_WORLD_WRITEABLE);
-------------------------------------------------------------------
android有一套自己的安全模型,當應用程式(.apk)在安裝時系統就會分配給他一個userid,
當該應用要去訪問其他資源比如檔案的時候,就需要userid匹配。預設情況下,任何應用創
建的檔案,sharedpreferences,資料庫都應該是私有的(位於/data/data/<package
name>/files),其他程式無法訪問。除非在建立時指定了Context.MODE_WORLD_READABLE或
者Context.MODE_WORLD_WRITEABLE ,只有這樣其他程式才能正確訪問。
----------------------------------------------------------------------
1.資料的讀取:
用資料的輸入流
----------------------
在FileService.java中新增讀取內容的方法
/**
* 檔案讀取內容
* @param filename 檔名
* @return
* @throws Exception
*/
public String read(String filename) throws Exception{
FileInputStream inputStream=context.openFileInput(filename);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
//這個方法會在/data/data/<package name>/files目錄下查詢這個檔案
//如果找到了就返回一個輸入流
byte[] buffer=new byte[1024];
//inputStream.read(buffer);//讀滿這個陣列後返回
//只要資料沒有讀完,需要一直呼叫這個方法
//這個方法的返回值為-1的時候,是讀完了,不是-1的時候返回的是
//讀取的大小位元組
int len=0;
while ((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len); //把讀取的資料放到記憶體中
}
byte[] data=outputStream.toByteArray();
return new String(data);
}
---------------------------------------------------------------
編寫測試類:readTest.java
package com.credream.file;
import com.credream.service.FileService;
import android.test.AndroidTestCase;
import android.util.Log;
public class readTest extends AndroidTestCase
{
private static final String TAG="FileServiceTest";
public void testRead()throws Exception{
FileService service=new FileService(this.getContext());
String result=service.read("lidewei.txt");
Log.i(TAG, result);
}
}
-------------------------------------------------------------
AndroidManifest.xml
清單檔案中新增測試junit支援包
<?xml version="1.0" encoding="utf-8"?>
package="com.credream.file"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".FileActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="android.test.runner" />
</application>
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.credream.file" />
</manifest>
---------------------------------------------------------------
右鍵測試,並用過濾器檢視:03-05 00:31:17.771: I/FileServiceTest(7453):
www.credream.com