需求:
模仿登录应用时的记住用户名和密码的操作
思路:
文件读写还是JavaSE的基础知识,不同的是需要了解android获取相应路径的API,以及判断SD卡状态的API,当然权限申请时必不可少的
文件可以写到cache下,也可以写到files下,这次测试写到files下
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="com.mrseng.fileoptdemo.MainActivity">
<EditText
android:layout_marginTop="10dp"
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用户名"/>
<EditText
android:id="@+id/et_password"
android:inputType="textPassword"
android:layout_marginTop="10dp"
android:layout_below="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"/>
<CheckBox
android:id="@+id/cb_remmber"
android:layout_below="@+id/et_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住我"/>
<Button
android:layout_centerHorizontal="true"
android:layout_alignBaseline="@+id/cb_remmber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
android:onClick="login"/>
</RelativeLayout>
Activity:
package com.mrseng.fileoptdemo;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
//声明全局变量
private EditText et_username, et_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//得到用户名和密码框
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
//回显
// readAccount_InnerMemory();
readAccount_SDCard();
}
/**
* 测试文件读写操作
*/
public void login(View v) {
//读取用户名和密码
String username = et_username.getText().toString();
String password = et_password.getText().toString();
//判断复选框是否选中
CheckBox cb_remmeber = (CheckBox) findViewById(R.id.cb_remmber);
if (cb_remmeber.isChecked()) {
//写入到内部存储空间
// writeInfo2InnerMemory(username,password);
//写入到sd卡
writeInfo2SDCard(username,password);
}
//提示登陆成功
Toast.makeText(this, "登陆成功!", Toast.LENGTH_SHORT).show();
}
/**
* 将登录信息写入到sd卡
*/
private void writeInfo2SDCard(String username,String password) {
//判断sd卡状态 是否为已挂载
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//获取外部存储空间
File file = new File(Environment.getExternalStorageDirectory(),"userinfo.txt");
FileOutputStream fos = null;
try{
//写入文件
fos = new FileOutputStream(file);
fos.write((username+"@@"+password).getBytes());
}catch (Exception e){
e.printStackTrace();
}finally {
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else {
Toast.makeText(this, "SD卡不可用!", Toast.LENGTH_SHORT).show();
}
}
/**
* 将登陆信息写入到内部存储空间
*/
private void writeInfo2InnerMemory(String username, String password) {
//将用户名密码写入到内部存储空间
File file = new File(getFilesDir(), "userinfo.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write((username + "@@" + password).getBytes());//加入特殊字符便于分割
fos.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 读取配置文件中的信息_SDCard
*/
private void readAccount_SDCard(){
File file = new File(Environment.getExternalStorageDirectory(),"userinfo.txt");
if(file.exists()){
FileInputStream input = null;
BufferedReader reader = null;
try {
input = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(input));
String text = reader.readLine();
String[] infos = text.split("@@");
et_username.setText(infos[0]);
et_password.setText(infos[1]);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 读取配置文件中的信息_内部存储空间
*/
private void readAccount_InnerMemory() {
//获取数据
File file = new File(getFilesDir(), "userinfo.txt");
if(file.exists()){//判断文件是否存在
FileInputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(inputStream));
String text = reader.readLine();
String[] info = text.split("@@");
et_username.setText(info[0]);
et_password.setText(info[1]);
} catch (Exception e) {
e.printStackTrace();
}finally {//关闭资源
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mrseng.fileoptdemo">
<!--申请读写外部存储空间的权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
使用SharedPreferences API来读写
write:
private void writeInfo2SharedPreferences(String username,String password){
//获取SharedPreferences
SharedPreferences sp = getSharedPreferences("info_sp",MODE_PRIVATE); //参数分别是文件名,文件权限
//获取编辑器
SharedPreferences.Editor editor = sp.edit();
editor.putString("username",username);
editor.putString("password",password);
//提交
editor.commit();
}
写入的路径是 data/data/packageName/shared_prefs/下。
read:
private void readAccount_SharedPreferences(){
//获取SharedPreferences
SharedPreferences sp = getSharedPreferences("info_sp",MODE_PRIVATE);
String username = sp.getString("username","");//参数是 要得到的值得key,如果没有得到的默认值
String password = sp.getString("password","");//所以就不用判断文件是否存在了。。。
et_username.setText(username);
et_password.setText(password);
}
其他注意:
新版本的android系统没有提供卸载sd卡功能,可以用android 2.3测试!