java - 如何在 .txt 文件中查找字符串,然后读取其后面的数据

标签 java java.util.scanner

有两个文件,一个是userData.txt,另一个是gameData.txt。在我的程序中,我为用户提供了两个选项。登录并注册。如果用户单击“注册”选项,那么我会询问他们想要保留的 ID 和密码并将其存储在 userData.txt 中。然后,我运行一个命令,生成一个随机字符串,该字符串将与用户的凭据一起存储在 userData.txt 和 gameData.txt 中。在gameData.txt中写入唯一 token 后,我将默认分配0个硬币。它将如下所示:

Akshit,乔希,687fd7d1-b2a9-4e4a-bc35-a64ae8a25f5b(在 userData.txt 中)

687fd7d1-b2a9-4e4a-bc35-a64ae8a25f5b,0(在gameData.txt中)

现在,如果用户单击登录选项,程序就会验证 userData.txt 中的数据。它还读取凭据后的唯一 token ,然后将其存储到名为 uniUserID 的变量中。

现在是我陷入困境的部分了。我将此 uniUserID 与 gameData.txt 文件中的数据进行比较。 Scanner 逐行读取 gameData.txt 并将 uniUserID 与其进行比较。我想要的是,如果它找到ID,那么它应该读取它后面的硬币(即0)并将其存储到名为硬币的变量中。但它向我抛出了一个类似“NoSuchElementException”的错误

这是代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.UUID;


public class Verification
{
    static File credentials = new File ("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\userData.txt"); //Clarifying filepath
    static String uniUserID = " ";
    static File gameData = new File ("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\gameData.txt");

    public boolean Verify (String ID,String Pass)
    {
        String tempName = " ";           //the data read from the .txt file would be stored in these temporary variables
        String tempPass = " ";
        boolean found = false;//declaring some boolean variables so that the do while and if else statements work smoothly
        boolean verified = false;

        try //Try and catch block is initialized in case the file is not found
        {
            do
            {
                Scanner s2 = new Scanner(credentials); //Reading the .txt file
                s2.useDelimiter("[,\n]");// The file reader will stop once it encounters any of the following delimiters
                while (s2.hasNext() && !found)
                {
                    tempName = s2.next();                     //assigning the data read from the file to these variables
                    tempPass = s2.next();
                    uniUserID= s2.next();
                    if (tempName.trim().equals(ID) && tempPass.trim().equals(Pass))//comparing the data read from the file and the data entered by the user
                    {
                        verified = true;
                        found = true;
                    }
                }
            }
            while (found = false);
        }
        catch (Exception ex)
        {
            System.out.println("Error");
        }

        return verified;
    }
    public void Write (String newUser, String newPass) {
        String uniID = " ";
        try {// try catch is used in case the file is not found
            uniID = UUID.randomUUID().toString();
            FileWriter writer = new FileWriter(credentials, true);// initializing the FileWriter, to make sure that it doesn't overwrite true is used so that it appends
            BufferedWriter buffwrite = new BufferedWriter(writer);                    // creating buffered writer object
            buffwrite.write("\n");                          // Writing the new user's credentials into the .txt file
            buffwrite.write(newUser);
            buffwrite.write(",");
            buffwrite.write(newPass);
            buffwrite.write(",");
            buffwrite.write(uniID);
            buffwrite.close();
        } catch (Exception ex) {
            System.out.println("Error");
        }
        try
        {
            FileWriter writer2 = new FileWriter(gameData, true);
            BufferedWriter buffwrite2 = new BufferedWriter(writer2);
            buffwrite2.write("\n");
            buffwrite2.write(uniID);
            buffwrite2.write(",");
            buffwrite2.write("0");
            buffwrite2.close();
        }
        catch(Exception ex)
        {
            System.out.println("Error");
        }
    }

    public static void Game(String uniqueID) throws FileNotFoundException
    {
        Scanner s3 = new Scanner (gameData);
        String waste = " ";
        String coins = " ";
        while (s3.hasNextLine())
        {
            String fileLine = s3.nextLine();
            if(fileLine.contains(uniUserID))
            {
                s3.useDelimiter(("[\n]"));
                s3.skip(uniUserID);
                coins = s3.next();
                
            }
        }
        System.out.println(coins);
    }
    public static void main(String[] args) throws FileNotFoundException {
        Verification obj = new Verification();
        Scanner s1 = new Scanner(System.in);                                                   //Creating scanner object
        boolean end = false;                                    //declaring the variable that will end the do while loop
        do                          //do while loop is used so that the user gets taken to the main menu again and again
        {
            System.out.println("Welcome to the economic bot!");
            System.out.println("Select one option to proceed");
            System.out.println("1. Login");
            System.out.println("2. Register");
            int choice = s1.nextInt(); //accepting user's choice

            switch (choice) {
                case 1:
                    System.out.println("Enter your username:");
                    String userID = s1.next();                                                //taking user credentials
                    System.out.println("Enter your password");
                    String userPass = s1.next();

                    boolean validated = obj.Verify(userID,userPass);

                    if (validated == true) { //if the login details are correct
                        System.out.println("Login Successful!");
                        System.out.println("Redirecting...");
                        System.out.println();
                        end = true;
                        Game(uniUserID);
                    }
                    else { //if the details entered are wrong
                        System.out.println("Login failed! Possibly due to wrong user credentials.");
                        System.out.println("Please try again!");
                    }
                    break;

                case 2:
                    System.out.println("Enter the username you'd like to keep:");
                    String regUserID = s1.next(); //accepting user details
                    System.out.println("Enter the password:");
                    String regUserPass = s1.next();

                    obj.Write(regUserID,regUserPass);
                    break;

                default:
                    System.out.println("Invalid Option chosen.");              // In case the user enters a wrong choice
            }
        }
        while (!end); // condition for the initial do loop
    }
}

最佳答案

尝试下面的代码:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.UUID;


public class Verification {
    static File credentials = new File("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\userData.txt"); //Clarifying filepath
    static String uniUserID = " ";
    static File gameData = new File("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\gameData.txt");

    public boolean Verify(String ID, String Pass) {
        String tempName = " ";           //the data read from the .txt file would be stored in these temporary variables
        String tempPass = " ";
        boolean found = false;//declaring some boolean variables so that the do while and if else statements work smoothly
        boolean verified = false;

        try //Try and catch block is initialized in case the file is not found
        {
            do {
                Scanner s2 = new Scanner(credentials); //Reading the .txt file
                s2.useDelimiter("[,\n]");// The file reader will stop once it encounters any of the following delimiters
                while (s2.hasNext() && !found) {
                    tempName = s2.next();                     //assigning the data read from the file to these variables
                    tempPass = s2.next();
                    uniUserID = s2.next();
                    if (tempName.trim().equals(ID) && tempPass.trim().equals(Pass))//comparing the data read from the file and the data entered by the user
                    {
                        verified = true;
                        found = true;
                    }
                }
            }
            while (found = false);
        } catch (Exception ex) {
            System.out.println("Error");
        }

        return verified;
    }

    public void Write(String newUser, String newPass) {
        String uniID = " ";
        try {// try catch is used in case the file is not found
            uniID = UUID.randomUUID().toString();
            FileWriter writer = new FileWriter(credentials, true);// initializing the FileWriter, to make sure that it doesn't overwrite true is used so that it appends
            BufferedWriter buffwrite = new BufferedWriter(writer);                    // creating buffered writer object
            buffwrite.write("\n");                          // Writing the new user's credentials into the .txt file
            buffwrite.write(newUser);
            buffwrite.write(",");
            buffwrite.write(newPass);
            buffwrite.write(",");
            buffwrite.write(uniID);
            buffwrite.close();
        } catch (Exception ex) {
            System.out.println("Error");
        }
        try {
            FileWriter writer2 = new FileWriter(gameData, true);
            BufferedWriter buffwrite2 = new BufferedWriter(writer2);
            buffwrite2.write("\n");
            buffwrite2.write(uniID);
            buffwrite2.write(",");
            buffwrite2.write("0");
            buffwrite2.close();
        } catch (Exception ex) {
            System.out.println("Error");
        }
    }

    public static void Game(String uniqueID) throws FileNotFoundException {
        Scanner s3 = new Scanner(gameData);
        String waste = " ";
        String coins = " ";
        while (s3.hasNextLine()) {
            String fileLine = s3.nextLine();
            if (fileLine.contains(uniUserID)) {
                /*s3.useDelimiter(("[\n]"));
                s3.skip(uniUserID);
                coins = s3.next();*/
                coins = fileLine.split(",")[1];
                break;
            }
        }
        System.out.println(coins);
    }

    public static void main(String[] args) throws FileNotFoundException {
        Verification obj = new Verification();
        Scanner s1 = new Scanner(System.in);                                                   //Creating scanner object
        boolean end = false;                                    //declaring the variable that will end the do while loop
        do                          //do while loop is used so that the user gets taken to the main menu again and again
        {
            System.out.println("Welcome to the economic bot!");
            System.out.println("Select one option to proceed");
            System.out.println("1. Login");
            System.out.println("2. Register");
            int choice = s1.nextInt(); //accepting user's choice

            switch (choice) {
                case 1:
                    System.out.println("Enter your username:");
                    String userID = s1.next();                                                //taking user credentials
                    System.out.println("Enter your password");
                    String userPass = s1.next();

                    boolean validated = obj.Verify(userID, userPass);

                    if (validated == true) { //if the login details are correct
                        System.out.println("Login Successful!");
                        System.out.println("Redirecting...");
                        System.out.println();
                        end = true;
                        Game(uniUserID);
                    } else { //if the details entered are wrong
                        System.out.println("Login failed! Possibly due to wrong user credentials.");
                        System.out.println("Please try again!");
                    }
                    break;

                case 2:
                    System.out.println("Enter the username you'd like to keep:");
                    String regUserID = s1.next(); //accepting user details
                    System.out.println("Enter the password:");
                    String regUserPass = s1.next();

                    obj.Write(regUserID, regUserPass);
                    break;

                default:
                    System.out.println("Invalid Option chosen.");              // In case the user enters a wrong choice
            }
        }
        while (!end); // condition for the initial do loop
    }
}

建议:

  1. 尝试在每行末尾而不是开头添加一个新行 (\n) 字符,因为它会在文件开头添加一个空行。
  2. 如果找到 ID 匹配,则中断循环。

关于java - 如何在 .txt 文件中查找字符串,然后读取其后面的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70605738/

相关文章:

java - 如何使用正则表达式替换字符

java.lang.IllegalStateException : ViewPager 错误

java - 从扫描仪读取并跳过空格

java - 为 Scanner 方法编写模式

java - 异步div

java - 使用 Java 从字符串中提取标记

java - Android - 将值从 HTML 或 Javascript 传递到 Java 的最简单方法?

java - while 循环第二次迭代中的 Scanner NoSuchElementException

java - 坚持创建一个新对象

java - 将一行中的所有整数扫描到 ArrayList 中