我正在尝试编写用户登录的代码,但问题是我不知道如何用Java读取文件。我有一个文本文件,其中包含用户名和密码,如下所示: 管理员:密码 好吧,我需要使用用户名“admin”来检查我的第一个 JTextField 和密码“password”来检查我的第二个 JTextField。当我单击登录按钮时将执行此操作。因为这些是我的代码的核心。
JTextField UserName = new JTextField("Enter Your UserName");
JTextField Password = new JTextField("Enter Your Password");
JButton Login = new JButton ("Login");
感谢任何帮助。
最佳答案
您可以这样逐行读取文件:
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;
}
}
关于java - 从 Java 文本文件中读取直到特定点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23137298/