Android儲存使用者名稱和密碼

來源:互聯網
上載者:User

標籤:

我們不管在開發一個項目或者使用別人的項目,都有使用者登入功能,為了讓使用者的體驗效果更好,我們通常會做一個功能,叫做儲存使用者,這樣做的目地就是為了讓使用者下一次再使用該程式不會重新輸入使用者名稱和密碼,這裡我使用3種方式來儲存使用者名稱和密碼

1、通過普通 的txt文本儲存

2、通過properties屬性檔案進行儲存

3、通過SharedPreferences工具類儲存

第一種:

/**     * 儲存使用者名稱和密碼的業務方法     *      * @param username     * @param password     * @return     */    public static boolean saveUserInfo(String username, String password) {        try {            // 使用當前項目的絕對路徑            File file = new File("data/data/com.example.android_file_handler/info.txt");            // 建立輸出資料流對象            FileOutputStream fos = new FileOutputStream(file);            // 向檔案中寫入資訊            fos.write((username + "##" + password).getBytes());            // 關閉輸出資料流對象            fos.close();            return true;        } catch (Exception e) {            throw new RuntimeException();        }    }

這裡寫的路徑是當前項目的絕對路徑,這樣做是有缺陷的,比如你將項目路徑改了,這裡的路徑就擷取就失敗了,所以Android提供了通過上下文一個方法擷取當前項目的路徑

public static boolean saveUserInfo(Context context, String username,            String password) {        try {            // 使用Android上下問擷取當前項目的路徑            File file = new File(context.getFilesDir(), "userinfo.txt");            // 建立輸出資料流對象            FileOutputStream fos = new FileOutputStream(file);            // 向檔案中寫入資訊            fos.write((username + "##" + password).getBytes());            // 關閉輸出資料流對象            fos.close();            return true;        } catch (Exception e) {            throw new RuntimeException();        }    }

上面這兩個方法都是儲存使用者名稱和密碼,接下來是擷取使用者名稱和密碼

/**     * 擷取普通txt檔案資訊     *      * @param context     * @return     */    public static Map<string, object=""> getTxtFileInfo(Context context) {        try {            // 建立FIle對象            File file = new File(context.getFilesDir(), "userinfo.txt");            // 建立FileInputStream對象            FileInputStream fis = new FileInputStream(file);            // 建立BufferedReader對象            BufferedReader br = new BufferedReader(new InputStreamReader(fis));            // 擷取檔案中的內容            String content = br.readLine();            // 建立Map集合            Map<string, object=""> map = new HashMap<string, object="">();            // 使用儲存資訊使用的##將內容分割出來            String[] contents = content.split("##");            // 儲存到map集合中            map.put("username", contents[0]);            map.put("password", contents[1]);            // 關閉流對象            fis.close();            br.close();            return map;        } catch (Exception e) {            e.printStackTrace();            return null;        }    }

這裡我將擷取到的內容封裝到Map集合中,其實使用普通的txt文本儲存使用者名稱和密碼是有缺陷的,這裡我是通過“##”來分割使用者名稱和密碼的,那麼如果使用者在密碼中的字元又包含了“#”這個特殊符號,那麼最後在擷取時,則擷取不倒原來儲存的資訊,所以個人認為dier中方法就可以解決這個問題

第二種:

使用屬性檔案儲存使用者名稱和密碼

/**     * 使用屬性檔案儲存使用者的資訊     *      * @param context 上下文     * @param username 使用者名稱     * @param password  密碼     * @return     */    public static boolean saveProUserInfo(Context context, String username,            String password) {        try {            // 使用Android上下問擷取當前項目的路徑            File file = new File(context.getFilesDir(), "info.properties");            // 建立輸出資料流對象            FileOutputStream fos = new FileOutputStream(file);            // 建立屬性檔案對象            Properties pro = new Properties();            // 設定使用者名稱或密碼            pro.setProperty("username", username);            pro.setProperty("password", password);            // 儲存檔案            pro.store(fos, "info.properties");            // 關閉輸出資料流對象            fos.close();            return true;        } catch (Exception e) {            throw new RuntimeException();        }    }

讀取屬性檔案

/**     * 返回屬性檔案對象     *      * @param context 上下文     * @return     */    public static Properties getProObject(Context context) {        try {            // 建立File對象            File file = new File(context.getFilesDir(), "info.properties");            // 建立FileIutputStream 對象            FileInputStream fis = new FileInputStream(file);            // 建立屬性對象            Properties pro = new Properties();            // 負載檔案            pro.load(fis);            // 關閉輸入資料流對象            fis.close();            return pro;        } catch (Exception e) {            e.printStackTrace();            return null;        }    }

在主方法中調用即可

// 擷取屬性檔案對象         Properties pro=LoginService.readSDCard(this);        // 擷取使用者名稱或密碼        if (null != pro) {            String username=pro.getProperty("username");            String password=pro.getProperty("password");            // 如果擷取到的使用者名稱或密碼不為空白,則設定到文字框中            if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {                // 設定使用者名稱                etUsername.setText(username);                // 設定密碼                etPassword.setText(password);            }        }

 

第三種:

使用SharedPreferences儲存使用者名稱和密碼

/**     * 使用SharedPreferences儲存使用者登入資訊     * @param context     * @param username     * @param password     */    public static void saveLoginInfo(Context context,String username,String password){        //擷取SharedPreferences對象        SharedPreferences sharedPre=context.getSharedPreferences("config", context.MODE_PRIVATE);        //擷取Editor對象        Editor editor=sharedPre.edit();        //設定參數        editor.putString("username", username);        editor.putString("password", password);        //提交        editor.commit();    }

在主方法中讀取:

SharedPreferences sharedPre=getSharedPreferences("config", MODE_PRIVATE);        String username=sharedPre.getString("username", "");        String password=sharedPre.getString("password", "");

使用普通txt檔案與屬性檔案儲存都是儲存到內部存放裝置中,我們也可以儲存的SDCard中,使用Android提供的Environment類就可以擷取到外部存放裝置

File file=new File(Environment.getExternalStorageDirectory(),"info.properties");

如果要使用絕對路徑

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

最後就是需要添加許可權,因為擷取外部存放裝置是有關安全的,所以需要添加相關的許可權

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

使用這幾種方法就可以實現儲存使用者名稱和密碼這個功能了,至於有沒有其他的方法,我想這幾種應該就夠用了

Android儲存使用者名稱和密碼

聯繫我們

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