A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 侯丛政 中级黑马   /  2013-2-14 00:01  /  1202 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class UserOperator {
        private static File file = new File("user.txt");            //  这段代码是登陆系统的用户操作类     疑问是 : 此处定义为static    用意何在呢 ?

        public boolean login(String username, String password) {
                boolean flag = false;
                BufferedReader br = null;
                try {
                        br = new BufferedReader(new FileReader(file));

                        String line = null;
                        while ((line = br.readLine()) != null) {
                                String data = line;
                                String[] strArray = data.split("=");
                                if (strArray[0].equals(username)
                                                && strArray[1].equals(password)) {
                                        flag = true;
                                        break;
                                }
                        }
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        if (br != null) {
                                try {
                                        br.close();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }
                return flag;
        }


        public void regist(User user) {
                BufferedWriter bw = null;
                try {
                        bw = new BufferedWriter(new FileWriter(file,true));
                        String data = user.getUsername() + "=" + user.getPassword();
                        bw.write(data);
                        bw.newLine();
                        bw.flush();
                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        if (bw != null) {
                                try {
                                        bw.close();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }
        }
}

1 个回复

倒序浏览
设置静态是因为我们每次调用这个函数都是在最后一次的文件改动上操作, 而不是将其整个替换掉.
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马