java 用文件实现登录功能

【描述】:

        在使用java语言来实现一些简单的管理系统时,常常需要使用文件的相应知识来实现登录功能。

        也即是在用户/管理员登录系统时,系统需要检测用户/管理员输入的用户名、账号和密码是否正确,只有当用户名、账号和密码全部输入正确的时候,才可以登录成功。

        在这篇文章中,我以用户登录作为例子来进行展示

【代码】:

public static void userLogin() throws IOException {//用户登录
		@SuppressWarnings("resource")
		Scanner sc=new Scanner(System.in);
		while(true) {
			System.out.println("==============管理员登录页面==============");
			System.out.print("请输入姓名:");
			String name=sc.nextLine();
			System.out.print("请输入密码:");
			String code=sc.nextLine();
			if(check1(name,code)==true) {//检查输入的姓名或者密码是否正确
				System.out.println("登录成功!");
				userMenu();
				break;
			}
			else {
				System.out.println("密码错误或者用户名错误,请重新输入!");
			}
		}
	}
	private static boolean check1(String name,String code) throws IOException {
		String dir="D:/programming/MyJava/用户信息.txt";
		File file=new File(dir);
		if(!file.exists()){
			file.createNewFile();
		}
		@SuppressWarnings("resource")
		BufferedReader b=new  BufferedReader(new FileReader(file));
		String temp=null;
		temp=b.readLine();//先读取一行
		while(temp!=null) {
			String sbstring=temp.toString();//转化为String
			int n=sbstring.length();//测字符串长度
			String []message=new String[2];
			int k=0;
			for(int i=0;i<2;i++) {
				message[i]="";
			}
			for(int i=0;i<n;i++) {
				if(sbstring.charAt(i)==',') {
					k++;
				}
				else {
					message[k]+=sbstring.charAt(i);
				}
				//System.out.print(sbstring.charAt(i));
			}
			if(name.equals(message[0])&&code.equals(message[1])) {
				return true;
			}
			temp=b.readLine();
		}
		return false;	
	}

【解释】:

        charAt()方法用户返回指定索引处的字符,索引范围为0~length()-1;因此数组message[0]中存储的是第一个分号(,)前的信息,message[1]中存储的是第一个分号后的信息。(如果你文件中的信息只有两列的话,也就是每一行只需要一个分号的情况。)

不明白的小伙伴可以自己动手输出一下,会发现System.out.println(message[0])输出的是第一列的全部信息,而System.out.println(message[1])输出的是第二列的全部信息。

扫描二维码关注公众号,回复: 17325108 查看本文章

猜你喜欢

转载自blog.csdn.net/ZQY211210400628/article/details/130937042
今日推荐