【问题标题】:Searching for username and password along with other variables in a text file?在文本文件中搜索用户名和密码以及其他变量?
【发布时间】:2019-02-15 06:56:56
【问题描述】:

我正在尝试读取一个名为 UserDetails.txt 的文本文件。

文本文件的每一行如下:

John : Doe : Seattle : jd3 : 1234

Jane : Doe : Olympia : jd4 : 5678 

其中最后两个变量是我要搜索的用户名和密码。

我的代码:

public class LoginFrame extends javax.swing.JFrame 
{


private static Scanner keyboard = new 
Scanner(System.in);
String username;
String password;
String filePath = "UserDetails.txt";

public LoginFrame() {
    initComponents();
}

private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {                                             
    username = jTextFieldUsername.getText();
    password = jTextFieldPassword.getText();
    verifyLogin(username,password,filePath);
   }                                            

public static void verifyLogin(String username, 
String password, String filepath)
{
   boolean match = false;
   String tempUserName = "";
   String tempPassword = "";
   try
   {
       keyboard = new Scanner(new 
       File(filepath));
       keyboard.useDelimiter("[:\n]");

       while(keyboard.hasNext() && !match)
       {
           tempUserName = keyboard.next();
           tempPassword = keyboard.next();

           if(tempUserName.trim().equals(username.trim()) && tempPassword.trim().equals(password.trim()))
           {
               match = true;
           }
       }
       keyboard.close();
       System.out.print(match);
   }
   catch (Exception e)
   {
       System.out.print("Error");
   }
}

我遇到的问题是我不确定如何将用户名和密码与用户的名字和姓氏分开。只有当用户名和密码是文本文件中仅有的两个变量时(除去了名字和姓氏),分隔符的使用才能找到这两个特定值。

【问题讨论】:

  • 是固定格式的字符串吗? firstname:lastname:city:username:password ,或者格式可以不同?
  • 格式在整个文本文件中是固定的。
  • 所以使用分隔符 ':' 你可以在数组中输入,并且可以为用户名密码或任何其他信息获取相应的值

标签: java jframe delimiter readfile file-search


【解决方案1】:

阅读整行,然后就可以使用了

    String str = "John : Doe : Seattle : jd3 : 1234"; // input line that you read from file
    String[] arr = str.split(" : ");
    String username = arr[3]; // as index starts from 0;
    String password = arr[4]; // similarly you can get other values

将其转换为字符串数组,该数组的用户名位于索引 3 和索引 4 处的密码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2012-07-27
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多