Android 简单的账号密码登陆界面(IO流)

Android 简单的账号密码登陆界面(IO流)
用到了map 、IO流等。
MainActivity代码如下:
package com.xh.tx.fileio;

import java.io.File;
import java.util.Map;

import com.xh.tx.utils.FileIOUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity  implements OnClickListener{

	EditText number = null;
	EditText pwd = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		number = (EditText) findViewById(R.id.number);
		pwd = (EditText) findViewById(R.id.pwd);
		Button btn = (Button) findViewById(R.id.btn);
		
		Map infos = FileIOUtils.readFile(new File(this.getFilesDir(),"rember.txt"));
		if(null != infos)
		{
			number.setText(infos.get("number"));
			pwd.setText(infos.get("pwd"));
		}
		
		btn.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		String num = number.getText().toString();
		String pwds = pwd.getText().toString();
		
		String content = num + "#" + pwds;
		
		File file = new File(this.getFilesDir(),"rember.txt");
		//File file = new File(this.getCacheDir(),"rember.txt");
		
		boolean status = FileIOUtils.writeFile(file, content);
		
		if(status)//如果保存成功那么提示保存成功,否则提示失败
		{
			Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
		}else
		{
			Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
		}
	}

}

读取写入到文件的代码如下:
package com.xh.tx.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class FileIOUtils
{
	public static boolean writeFile(File file, String content)
	{
		//data/data/com.xh.tx.fileio
		FileOutputStream out  = null;
		try {
			out = new FileOutputStream(file);
			
			out.write(content.getBytes());//byte[205]
			
			return true;
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null != out)
				{
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		return false;
	}
	
	public static Map readFile(File file)
	{
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			
			String content = reader.readLine();
			String[] info = content.split("#");
			
			Map infos = new HashMap();
			infos.put("number", info[0]);
			infos.put("pwd", info[1]);
			
			return infos;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

布局文件:



   
   
   
   
   
   


你可能感兴趣的:(Android 简单的账号密码登陆界面(IO流))