【问题标题】:Reading till a specific point from text file in Java从Java中的文本文件中读取直到特定点
【发布时间】:2014-04-17 15:32:07
【问题描述】:

我正在尝试为用户登录编写代码,但问题是我不知道如何在 Java 中读取文件。我有一个包含用户名和密码的文本文件,如下所示; 管理员:密码 好吧,我需要使用用户名“admin”来检查我的第一个 JTextField 和密码“password”来检查我的第二个 JTextField。当我单击登录按钮时,将执行此操作。因为这些是我代码的核心。

JTextField UserName = new JTextField("Enter Your UserName");
JTextField Password = new JTextField("Enter Your Password");
JButton Login = new JButton ("Login");  

感谢您的帮助。

【问题讨论】:

    标签: java


    【解决方案1】:

    你可以这样逐行读取文件:

    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
       // process the line.
    }
    br.close();
    

    但您问题的完整答案是:

    public class Main {//change it as you wish
        final static String file = "Your file path";
        public static void main(String[] args) {
            final JTextField UserName = new JTextField("Enter Your UserName");
            final JTextField Password = new JTextField("Enter Your Password");
            JButton Login = new JButton ("Login"); 
    
    
            Login.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    // TODO Auto-generated method stub
                    String uName = UserName.getText();
                    String pass = Password.getText();
                    checkUserPass(uName, pass);//check them as you want
    
                }
            });
        }
        static boolean checkUserPass(String uName, String pass) {
            try(BufferedReader br = new BufferedReader(new FileReader(file))) {
                String line;
    
                // I assume your file contains just a line like      username:password
                if ((line = br.readLine()) != null) {
                    // process the line.
    
    
                    String[] tmp = line.split(":");
                    if (tmp[0].equals(uName) && tmp[1].equals(pass)) {
                        return true;
                    }
                    return false;
                }
            }catch (IOException e) {
    
            }
            return false;
    
        }
    }
    

    【讨论】:

    • 我怎样才能读到“:”以获取第一个单词作为用户名,然后在“:”之后获取第二个单词作为密码
    • 用 if 检查一下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多