Android簡單介紹SharedPreference,內部檔案,sdcard資料存放區,

來源:互聯網
上載者:User

Android簡單介紹SharedPreference,內部檔案,sdcard資料存放區,

SharedPreference

  以xml的結構儲存簡單的資料,儲存在data/data/程式包名/shared_prefs檔案夾中

  使用方式     

    建立對象的方式有三種

      Context 的 getSharedPreferences()

      Activity 的 getPreferences()

      PreferenceManager 的 getDefaultSharedpreferences()

    擷取資料

      sharedPrefs.getXXX()方法,如getInt(),getString()等

    儲存資料  擷取Editor對象 sharedPrefs.edit();

    存入資料  editor.putXXX()方法,如putInt()、putString()

    提交要儲存的資料    editor.commit()

我們通過路徑找檔案 看一下運行結果 路徑我在上面已經提到了  我使用的是Genymotion測試   

訪問手機內部儲存需要root許可權才可以訪問

 

 

 

 

 

 

 

內部儲存

    將資料儲存在記憶體空間中,資料使用者不能輕易訪問的地區,訪問需要root許可權。儲存在/data/data/程式包名/files檔案夾下

  使用方式

    其使用還是要通過FileInputStream和FileOutputStream對檔案File進行操作,只不過不是通過他們的構造方法來建立。

  擷取FileInputStream

    FileInputStream fis = openFileInput();        (Activity的方法)

    FileOuputStream fos = openFileOutput();         (Activity的方法)

      檔案File將會自動建立

 

外部SDCard儲存

在操作sd卡的時候需要在資訊清單檔中添加許可權

 

將資料儲存到SDCard卡中,任何程式都可以訪問,使用者也很容易查看、修改。

  使用方式

    通過FileInputStream和FileOutputStream對檔案File進行操作。

  SDCard操作類Environment      進行SDCard狀態擷取

    Environment.getExternalStorageState();    擷取擴充卡狀態

    Environment.MEDIA_MOUNTED    安裝的並可讀寫

    Environment.MEDIA_MOUNTED_READ_ONLY    安裝的但唯讀

    Environment.MEDIA_REMOVED        移除的

  擷取熱門檔案夾路徑

    Environment.getExternalStorageDirectory();    擷取擴充卡根資料夾

 這個路徑在sd卡下自己寫  找不到 只能輕輕說聲加油~

 

貼一個小demo

運行效果

在edittext 輸入文本點擊寫入按鈕   點擊讀取顯示到textview      重要的事情說三遍   加許可權~加許可權~加許可權~

 

activity_main.xml

  

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:orientation="vertical"    tools:context="com.example.lesson15_data_storage.MainActivity">    <CheckBox        android:id="@+id/push"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="是否追加到原檔案末尾"/>    <EditText        android:id="@+id/edit"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/text_view"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="顯示文本"/>    <Button        android:id="@+id/inner_storage"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="儲存文本到內部儲存中"        android:onClick="onClick"/>    <Button        android:id="@+id/inner_read"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="讀取內部儲存的文本到TextView"        android:onClick="onClick"/>    <Button        android:id="@+id/outter_read"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="onClick"        android:text="讀取擴充卡的文本到textview"/>    <Button        android:id="@+id/outter_write"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="onClick"        android:text="將文本寫入到擴充卡中"/></LinearLayout>

 

MainActivity

  

public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private CheckBox cbPush;    private TextView textView;    private EditText edit;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        cbPush= (CheckBox) findViewById(R.id.push);        textView= (TextView) findViewById(R.id.text_view);        edit= (EditText) findViewById(R.id.edit);        getSharedPreferences();    }    /**     * 儲存一個CheckBox的選中狀態     */    private void getSharedPreferences() {        //Context擷取  參數1檔案名稱  參數2檔案許可權        SharedPreferences preferences=getSharedPreferences("setting", Context.MODE_PRIVATE);        //activity擷取  檔案名稱是當前活動名        SharedPreferences preferences1=getPreferences(MODE_PRIVATE);        //擷取editor對象        SharedPreferences.Editor editor1=preferences1.edit();        //儲存資料        editor1.putString("text","通過activity對象擷取");        //提交資料        editor1.commit();        //PreferenceManager擷取  檔案名稱自動產生 存取權限預設私人        PreferenceManager.getDefaultSharedPreferences(MainActivity.this)                .edit()                .putString("text","通過PreferenceManager擷取")                .commit();        //參數1 key  參數2 預設值 基礎資料型別 (Elementary Data Type)要求不可以為空白 所以必須有預設值        boolean checked=preferences.getBoolean("cbPush",false);        cbPush.setChecked(checked);        cbPush.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {                //通過context擷取 參數1 儲存的檔案名稱  參數2 資料的存取權限                SharedPreferences sharedPreferences=getSharedPreferences("setting", Context.MODE_PRIVATE);                //擷取編輯器對象                SharedPreferences.Editor edit=sharedPreferences.edit();                //存入資料                edit.putBoolean("cbPush",isChecked);                //提交修改                edit.commit();            }        });    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.inner_storage:                write();//寫入到內部檔案                Toast.makeText(MainActivity.this,"寫入成功",Toast.LENGTH_SHORT).show();                break;            case R.id.inner_read:                read();//讀取內部檔案                Toast.makeText(MainActivity.this,"讀取成功",Toast.LENGTH_SHORT).show();                break;            case R.id.outter_read:                oread();//讀取sdcard檔案                Toast.makeText(MainActivity.this,"讀取成功",Toast.LENGTH_SHORT).show();                break;            case R.id.outter_write:                owrite();//寫入sdcard檔案                Toast.makeText(MainActivity.this,"寫入成功",Toast.LENGTH_SHORT).show();                break;        }    }    private void oread() {        String state=Environment.getExternalStorageState();        try {            //判斷是否讀寫 或唯讀            if(state.equals(Environment.MEDIA_MOUNTED)||state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)){                File sdcardRoot=Environment.getExternalStorageDirectory();                File read=new File(sdcardRoot,"my/text.txt");                if(read.exists()){                    FileInputStream fis=new FileInputStream(read);                    //位元組轉字元會進行位元組編碼的轉換  new InputStreamReader(fis,"utf-8") android預設utf-8                    BufferedReader reader=new BufferedReader(new InputStreamReader(fis));                    String str=reader.readLine();                    textView.setText(str);                    reader.close();                    fis.close();                }            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    private void owrite() {        try {            //擷取擴充卡狀態            String state= Environment.getExternalStorageState();            //是否可讀寫            if(state.equals(Environment.MEDIA_MOUNTED)){                //擷取擴充卡檔案夾目錄                File sdcardRoot=Environment.getExternalStorageDirectory();                File save=new File(sdcardRoot,"my/text.txt");                //判斷檔案是否存在                if (save.exists()){                }else{                    //判斷父級檔案夾是否存在                    if(!save.getParentFile().exists()){                        //建立檔案夾                        save.getParentFile().mkdirs();                    }                    //建立檔案                    save.createNewFile();                }                String text=edit.getText().toString();                //檔案是否在原檔案末尾追加 cbPush.isChecked() checkbox 是否選中                FileOutputStream fos=new FileOutputStream(save,cbPush.isChecked());                fos.write(text.getBytes("utf-8"));                fos.flush();                fos.close();//                //是否是檔案夾//                save.isDirectory();//                //是否是檔案//                save.isFile();//                //是否是隱藏檔案  檔案名稱以  .開頭的檔案//                save.isHidden();//                //擷取所有子檔案的檔案名稱數組//                save.list();//                //擷取所有子檔案的檔案數組//                save.listFiles();            }        } catch (IOException e) {            e.printStackTrace();        }    }    private void read() {        try {            //讀取寫入的檔案            FileInputStream fis=openFileInput("text.txt");            int len=-1;            byte [] b=new byte[1024];            ByteArrayOutputStream bos=new ByteArrayOutputStream();            while ((len=fis.read(b))!=-1){                bos.write(b,0,len);            }            textView.setText(bos.toString("utf-8"));            bos.close();            fis.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    private void write() {        try {            //擷取輸入框內容            String text=edit.getText().toString();            //判斷是否為空白            if(TextUtils.isEmpty(text))return;            //寫入方式  追加或覆蓋            int mode=cbPush.isChecked()?MODE_APPEND:MODE_PRIVATE;            //擷取FileOutputStream            FileOutputStream fos=openFileOutput("text.txt",mode);            //字串轉換為byte 寫入檔案            fos.write(text.getBytes("utf-8"));            fos.flush();            fos.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}

 

聯繫我們

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