如何在 .txt 文件中找到一个字符串,然后读取它后面的数据

How to find a String in a .txt file and then read the data after it

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

阿克希特,乔希,687fd7d1-b2a9-4e4a-bc35-a64ae8a25f5b(在 userData.txt)

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

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

现在是我卡住的部分。我将此 uniUserID 与 gameData.txt 文件中的数据进行比较。 Scanner 逐行读取 gameData.txt 并将 uniUserID 与其进行比较。我想要的是,如果它找到了 ID,那么它应该读取它后面的硬币(即 0)并将其存储到一个名为 coins 的变量中。但它抛出一个错误,类似于“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 匹配,则中断循环。

Game() 方法更改为:

{
        Scanner s3 = new Scanner (gameData);
        String waste = " ";
        String coins = " ";
        while (s3.hasNextLine())
        {
            String fileLine = s3.nextLine();
            if(fileLine.contains(uniUserID))
            {
                coins = fileLine.split(",")[1];
                break;
            }
        }
        System.out.println(coins);
    }

使用分隔符 (,) 简单地将线分成两部分,并得到包含硬币的第二部分

要添加更多硬币,请使用 BufferedWriter:

BufferedWriter writer = new BufferedWriter(new FileWriter(gameData));
writer.write(uniId+","+newCoins);
writer.close();

重要提示:从 FileWriter 对象中删除 true,因为您正在覆盖而不是追加