Android 在外部儲存讀寫檔案,android讀寫

來源:互聯網
上載者:User

Android 在外部儲存讀寫檔案,android讀寫

本文主要介紹android中如何在外部儲存讀寫資料

sd卡的路徑

sdcard:2.3之前的sd卡路徑

mnt/sdcard:4.3之前的sd卡路徑

storage/sdcard:4.3之後的sd卡路徑

開啟file explorer

可以看到sdcard是個空的檔案夾,因為這個檔案夾是個捷徑,指向/storag檔案夾,接著開啟storag檔案夾

讀寫sd卡

最簡單的開啟sd卡的方式

File file = new File("sdcard/info.txt");

* 寫sd卡需要許可權

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

運行程式

* 讀sd卡,在4.0之前不需要許可權,4.0之後可以設定為需要

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

通過api擷取sd卡的路徑

* 使用api獲得sd卡的真實路徑,部分手機品牌會更改sd卡的路徑

Environment.getExternalStorageDirectory()

* 判斷sd卡是否準備就緒

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))

完整代碼如下:

    public void saveAccount(String name, String pass) {        // 判斷sd卡狀態        if (Environment.getExternalStorageState().equals(                Environment.MEDIA_MOUNTED)) {            // 得到一個file對象,路徑是sd卡的真實路徑            File file = new File("sdcard/info.txt");            try {                FileOutputStream fos = new FileOutputStream(file);                fos.write((name + "##" + pass).getBytes());                fos.close();            } catch (Exception e) {                e.printStackTrace();            }        } else {            Toast.makeText(this, "sd卡不可用喲", 0).show();        }    }    public void loadAccount() {        File file = new File("sdcard/info.txt");        if (file.exists()) {            try {                FileInputStream fis = new FileInputStream(file);                // 把位元組流轉換為位元組流                BufferedReader br = new BufferedReader(new InputStreamReader(                        fis));                String text = br.readLine();                String[] s = text.split("##");                // 擷取使用者輸入的帳號和密碼                EditText et_name = (EditText) findViewById(R.id.et_name);                EditText et_pass = (EditText) findViewById(R.id.et_pass);                et_name.setText(s[0]);                et_pass.setText(s[1]);            } catch (Exception 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.