Android學習筆記---android資料存放區與訪問

來源:互聯網
上載者:User

資料存放區與訪問---------------------------------------一個在手機和sd卡上隱藏檔的例子1.a.檔案名稱:lable  b.一個text框  c.檔案內容:label  d.一個text框  e.儲存:button-----------------------------/File/res/layoutpackage 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. */@Overridepublic 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{  @Overridepublic 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.javapackage 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 j2eeFileOutputStream 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    =  0Context.MODE_APPEND    =  32768Context.MODE_WORLD_READABLE =  1Context.MODE_WORLD_WRITEABLE =  2Context.MODE_PRIVATE:為預設操作模式,代表該檔案是私人資料,只能被應用本身訪問, 在該模式下,寫入的內容會覆蓋原檔案的內容,如果想把新寫入的內容追加到原檔案中。可 以使用Context.MODE_APPENDContext.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.javapackage 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"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    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): 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.