从Java中的文本文件中读取特定点

时间:2014-04-17 15:32:07

标签: java

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

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

我感谢任何帮助。

1 个答案:

答案 0 :(得分: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;

    }
}