Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中如何把資料存到 sdcard

編輯:關於 Android 程式設計

在 Android 裡,sdcard 屬於外部儲存空間,是應用程式可讀寫的目錄,其他應用無權存取,通常用來存放一些安全性要求不高但體積較大的資料。

使用 sdcard 前的幾個注意事項

1. 權限問題

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

2. 透過 Environment 取得 sdcard 路徑

Environment.getExternalStorageDirectory().getPath();

3. 使用前先判斷掛載狀態

if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    Toast.makeText(mContext, "sdcard不存在或未掛載", Toast.LENGTH_SHORT).show();
    return;
}

4. 判斷剩餘空間是否足夠

File sdcard_file = Environment.getExternalStorageDirectory();
long usableSpace = sdcard_file.getUsableSpace();
String usableSpaceSize = Formatter.formatFileSize(this, usableSpace);
// 例如要下載 100M 的電影,空間不足則提示
if (usableSpace < 100 * 1024 * 1024) {
    Toast.makeText(mContext, "sdcard剩餘空間不足,剩餘:" + usableSpaceSize, 0).show();
    return;
}

實作案例:記住使用者名稱與密碼

下面用一個模擬登入頁的小範例,完整示範 sdcard 存取資料的過程。

① 布局檔

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入用戶名" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="15dp"
        android:hint="請輸入密碼"
        android:inputType="textPassword" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <CheckBox
            android:id="@+id/cb_rem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="記住密碼" />
        <Button
            android:id="@+id/btn_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:text="登 錄" />
    </RelativeLayout>
</LinearLayout>

② MainActivity

public class MainActivity extends Activity implements OnClickListener {
    private EditText et_password, et_username;
    private CheckBox cb_rem;
    private Button btn_login;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        et_password = (EditText) findViewById(R.id.et_password);
        et_username = (EditText) findViewById(R.id.et_username);
        cb_rem = (CheckBox) findViewById(R.id.cb_rem);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);

        // 再次進入時回顯已保存的資料
        Map<String, String> userInfo = UserInfoUtils.getUserInfo();
        if (userInfo != null) {
            et_username.setText(userInfo.get("username"));
            et_password.setText(userInfo.get("password"));
            cb_rem.setChecked(true);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                String password = et_password.getText().toString().trim();
                String username = et_username.getText().toString().trim();
                boolean isChecked = cb_rem.isChecked();
                if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
                    Toast.makeText(mContext, "用戶名密碼不能為空", 0).show();
                    return;
                }
                // 判斷可用空間
                File sdcard_file = Environment.getExternalStorageDirectory();
                long usableSpace = sdcard_file.getUsableSpace();
                if (usableSpace < 100 * 1024 * 1024) {
                    Toast.makeText(mContext, "sdcard剩餘空間不足", 0).show();
                    return;
                }
                if (isChecked) {
                    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        Toast.makeText(mContext, "sdcard沒有掛載或不可用", 0).show();
                    }
                    boolean result = UserInfoUtils.saveUserInfo(username, password);
                    Toast.makeText(mContext, result ? "用戶名密碼保存成功" : "用戶名密碼保存失敗", 0).show();
                }
                break;
        }
    }
}

③ 讀寫 sdcard 的工具類

public class UserInfoUtils {
    // 保存用戶資訊到 sdcard
    public static boolean saveUserInfo(String username, String password) {
        try {
            String userInfo = username + "##" + password;
            String path = Environment.getExternalStorageDirectory().getPath();
            File file = new File(path, "userinfo.txt");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(userInfo.getBytes());
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 從 sdcard 取出資料
    public static Map<String, String> getUserInfo() {
        try {
            String path = Environment.getExternalStorageDirectory().getPath();
            File file = new File(path, "userinfo.txt");
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String readLine = br.readLine();
            String[] split = readLine.split("##");
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("username", split[0]);
            map.put("password", split[1]);
            br.close();
            fis.close();
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

④ 驗證效果

輸入用戶名與密碼、勾選「記住密碼」並點擊登入,退出後再次進入,若資料成功回顯,就代表往 sdcard 存取資料的功能已經跑通了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved