从文本文件登录Java GUI

从文本文件登录Java GUI,java,swing,text-files,Java,Swing,Text Files,我想从一个名为“ClientData.txt”的文本文件登录,该文件使用第二行(用户名)和第三行(密码)以及“/”分隔符。但当我运行它时,他们似乎无法识别它。请帮忙这是我的代码: File Login = new File ("ClientData.txt"); try{ Scanner read = new Scanner (Login); read.useDelimiter("/"); while (read.nextLine() !=null) {

我想从一个名为“ClientData.txt”的文本文件登录,该文件使用第二行(用户名)和第三行(密码)以及“/”分隔符。但当我运行它时,他们似乎无法识别它。请帮忙这是我的代码:

File Login = new File ("ClientData.txt");
try{
    Scanner read = new Scanner (Login);
    read.useDelimiter("/");
    while (read.nextLine() !=null) {
        String user = read.next();
        read.next();
        if (jTextField1.getText().equals(user) && jPasswordField1.getText().equals(pass) && Clientbutton.isSelected()){
            new ClientMenu();
        }
    }
}   catch (FileNotFoundException ex) {
    JOptionPane.showMessageDialog(null, "Incorrect username or password");
}

该问题可能是由于具有相邻字符串的标记中包含了新行字符

e、 g。 文件

代币:(1)约翰,(2)史密斯01\n沃尔特,(3)艾萨克森01

解决方案:

  • 更改分隔符
    scanner.useDelimiter((/|\\r\\n |\\n\\r |\\r |\\n)”
    以包含新行字符

  • 使用拆分而不是设置分隔符:

    String line;
    while (scanner.hasNextLine() && !isBlank(line = scanner.nextLine())) {
    
         String[] accountData = line.split("/");
         String user = accountData[0];
         String password = accountData[1];
         System.out.println(user + ", " + password);
    }
    
    在这种情况下,首选
    BufferedReader
    类和
    BufferedReader.readLine()

    其中
    为空
    为:

    private static boolean isBlank(String s) {
         return s == null || s.isEmpty();
    }
    
  • private static boolean isBlank(String s) {
         return s == null || s.isEmpty();
    }