[安卓基础]数据存储之文件

比如在登录界面,用户输入的账号密码如何保存起来?

关于保存的路径有多个,这里先看看第一种情况,直接保存到系统给APP分配的专属空间data文件夹下,这种情况无需权限

这里必然要涉及到文件的读取和写入,java IO的具体知识需要好好看看


给一个checkbox来确定用户是否需要保存,打钩才保存,另外对onclick的处理有多种方式,这里采用在layout里加入onclick参数的方式

首先是button

<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"
    tools:context="${relativePackage}.${activityClass}" 
    android:orientation="vertical" >
    <EditText
        android:id="@+id/et_uername"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/et_password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <RelativeLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content" >
    <CheckBox 
         android:id="@+id/cb_remeber"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" 
         android:layout_alignParentLeft="true"/>
     <Button
        android:id="@+id/bt_login"      
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"  
        android:layout_alignParentRight="true"
        android:onClick="login"/>
    </RelativeLayout>
</LinearLayout>


实现的过程中有一些小细节需要注意

利用输出流向文本写入的时候,关于路径,可以用getCacheDir方法,省事一点;

checkbox要判断是否勾选了,勾上才保存,并且需要判断是否有输入,有输入才去判断是否勾选并保存

public class MainActivity extends Activity {
	EditText et_username =null;
	EditText et_password =null;
	Button bt_login =null;
	CheckBox cb_remeber = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
        //先获取到button		
		 et_username = (EditText) findViewById(R.id.et_uername);
		 et_password = (EditText) findViewById(R.id.et_password);
		 bt_login = (Button) findViewById(R.id.bt_login);
		 cb_remeber = (CheckBox) findViewById(R.id.cb_remeber);
		//读取	 
		 readAccount();
	}
	
	public void login(View v)  {
	 //打钩才保存
	 if(cb_remeber.isChecked()){
		//获取到用户名和密码
		String username= et_username.getText().toString();
		String password= et_password.getText().toString();
	   //将用户名和密码写入到文本
		//1.新建一个file对象,指向android的某个文件
		//应用向自己的专属空间内读写文件,是不需要申请权限的!
		 //麻烦一点的写法 File file = new File("/data/data/com.cskaoyan.login/userinfo.txt");
    	//省事的写法
		File file = new File(getCacheDir() ,"userinfo2.txt");
		//声明
		FileWriter fw=null;
		//2.新建一个文件的字符输出流 ,向该文件写入内容 
		 try {
			  fw  = new FileWriter(file);
			  fw.write(username+","+password); 		 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//3.关闭输出流 
			if (fw!=null)  
			try {
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	 }	
	}
	private void readAccount() {
		// TODO Auto-generated method stub
		 File file = new File(getCacheDir() ,"userinfo2.txt");
		 //判断文件是否存在,也就是说是否有输入号码
		 if (file.exists()) {
			 //声明
			 FileReader fReader = null;
			 BufferedReader br =null;
			 try {
				fReader = new FileReader(file);
				br = new BufferedReader(fReader);
				//按行读取并接收
	            String line= br.readLine();
	            //将用户名和密码分开 切割~
	            String[] s= line.split(",");
	            //返回数组,第一个元素和第二个元素
				String username = s[0]; 
				String passwrod = s[1]; 
	            et_username.setText(username); 
				et_password.setText(passwrod);				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally{				
				try {
					fReader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

另外,利用文件的形式保存数据,也可以写入到SD卡上,这个时候就需要读写权限

另外SD卡作为外设,必须要去判断是否已经挂载,正常挂载才能读写

另外由于SD卡容易满载,所以最好使用缓存的方式

整体来说与前面的区别不大

public class MainActivity extends Activity {
	EditText et_username =null;
	EditText et_password =null;
	CheckBox cb_remeber = null;
	Button bt_login =null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		 et_username = (EditText) findViewById(R.id.et_uername);
		 et_password = (EditText) findViewById(R.id.et_password);
		 cb_remeber = (CheckBox) findViewById(R.id.cb_remeber);
		 bt_login = (Button) findViewById(R.id.bt_login);	
		 readAccount();
	}
	private void readAccount() {
		// TODO Auto-generated method stub
		// 他们俩的区别,后者是缓存数据,如果内存满了,会自动清理掉,并且也可以手动选择清理缓存
		 /*File file = new File("getFilesDir(),userinfo.txt");
		 File file = new File("getCacheDir(),userinfo.txt");*/
		 File sdcard = Environment.getExternalStorageDirectory();
		 File file = new File(sdcard , "userinfo.txt");	
		 if (file.exists()) {
			 FileReader fReader = null;
			 BufferedReader br =null;
			 try {
				fReader = new FileReader(file);
				br = new BufferedReader(fReader);
	            String line = br.readLine();
	            String[] s= line.split(",");
				String username = s[0]; 
				String passwrod = s[1]; 
	            et_username.setText(username); 
				et_password.setText(passwrod);			
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally{			
				try {
					fReader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}		
	}
	public void login(View v)  {	
		if(cb_remeber.isChecked()){		
			String username= et_username.getText().toString();
			String password= et_password.getText().toString();
			File sdcard = Environment.getExternalStorageDirectory();
			//SD卡状态必须是挂载的才应该去读写
			if ("mounted".equals(Environment.getExternalStorageState())) {
				File file = new File(sdcard , "userinfo.txt"); 				
				FileWriter fw=null;
				//2.新建一个文件输出流 ,向该文件写入内容 
				 try {
					fw  = new FileWriter(file);
					fw.write(username+","+password); 				 
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					//3.关闭输出流 
					if (fw!=null)  
					try {
						fw.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} 		
		}	
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值