File size: 2,565 Bytes
0284885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package case_package1;

import java.io.*;
import java.util.Scanner;

public class Login {
    public static void main(String[] args) throws IOException {
        /*
            需求:写一个登录小案例

            步骤:
                将正确的用户名和密码手动保存在本地的userinfo.txt文件中
                保存格式为:username=zhangsan&password=123&count=0
                让用户键盘录入用户名和密码
                        比较用户录入的和正确的用户名密码是否一致
                如果一致则打印登录成功
                    如果不一致则打印登录失败
         */

        //1、读取正确的用户名和密码
        BufferedReader br = new BufferedReader(new FileReader("/Users/zhaoxiaoyong/Documents" +
                "/Java/IO_stream_project/Case_module/src/userinfo.txt"));
        String line = br.readLine();
        br.close();

        // username=zhangsan&password=123&count=0
        String[] userinfo = line.split("&");
        String[] arr1 = userinfo[0].split("=");
        String[] arr2 = userinfo[1].split("=");
        String[] arr3 = userinfo[2].split("=");

        String rightUsername = arr1[1];
        String rightPassword = arr2[1];
        int count = Integer.parseInt(arr3[1]);


        //2、用户键盘录入用户名和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();

        //3、比较
        if (rightUsername.equals(username) && rightPassword.equals(password) && count < 3) {
            System.out.println("登录成功");
        } else {
            count++;
            if (count < 3) {
                System.out.println("登录失败,还剩下" + (3 - count) + "次机会");
            } else {
                System.out.println("用户账户被锁定");
            }

            writeInfo("username=" + rightUsername + "&password=" + rightPassword + "&count=" + count);

        }


    }

    /*
     *   作用:
     *       写出一个字符串到本地文件中
     *   参数:
     *       要写的字符串
     * */
    private static void writeInfo(String content) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("/Users/zhaoxiaoyong/Documents/Java" +
                "/IO_stream_project/Case_module/src/userinfo.txt"));

        bw.write(content);
        bw.close();
    }
}