黑马程序员技术交流社区

标题: 关于static的应用问题 [打印本页]

作者: 侯丛政    时间: 2013-2-14 00:01
标题: 关于static的应用问题
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();
                                }
                        }
                }
        }
}


作者: 罗海云    时间: 2013-2-14 09:21
设置静态是因为我们每次调用这个函数都是在最后一次的文件改动上操作, 而不是将其整个替换掉.




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2