How to read a specified String from an input file, then read the next word after it

…衆ロ難τιáo~ 提交于 2019-12-24 03:27:37

问题


In Java I want to be able to have two JTextFields that take in String. One is a username and the other a password. to "login", the program will search through a file --> accounts.txt and will search first for "usrnm:", once it finds it, it takes the word right after the : the same goes for the password but it searches for "pswrd:".

Here's what iv'e got so far:

    public void checkCredentials() {
    try {
        BufferedReader br = new BufferedReader(new FileReader(new File("accounts.txt")));
        String text = br.readLine();
        text = text.toLowerCase();
        text.split("usrnm:");
        System.out.println("username: " + userInput);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

any help is appreciated!


回答1:


Instead of searching the file twice I believe that its better to save first the username and on the next line the password. While you read them you can create User objects that will have the following attributes (a username and a password (String)). Also you could keep those into a linked list while your system is active. So that you could easily access the user accounts. Once a user needs to log in you will scan the list and by using the userList.get(i).equals(textfield.getText()) you will determine the user asked. Afterwards, if the above statement holds true you will check if the userList.get(i).getPassword().equals(textfield2.getText()) is true and grant or deny the access accordingly.

I am providing some useful parts below.

    public void readFromFile(String fileName, ListInterface<User> userList) {
        String oneLine, oneLine2;
        User user;
        try {
            /*
             * Create a FileWriter object that handles the low-level details of
             * reading
             */
            FileReader theFile = new FileReader(fileName);

            /*
             * Create a BufferedReader object to wrap around the FileWriter
             * object
             */
            /* This allows the use of high-level methods like readline */
            BufferedReader fileIn = new BufferedReader(theFile);

            /* Read the first line of the file */
            oneLine = fileIn.readLine();
            /*
             * Read the rest of the lines of the file and output them on the
             * screen
             */
            while (oneLine != null) /* A null string indicates the end of file */
            {
                oneLine2 = fileIn.readLine();
                user = new User(oneLine, oneLine2);
                oneLine = fileIn.readLine();
                userList.append(user);
            }

            /* Close the file so that it is no longer accessible to the program */
            fileIn.close();
        }

        /*
         * Handle the exception thrown by the FileReader constructor if file is
         * not found
         */
        catch (FileNotFoundException e) {
            System.out.println("Unable to locate the file: " + fileName);
        }

        /* Handle the exception thrown by the FileReader methods */
        catch (IOException e) {
            System.out.println("There was a problem reading the file: "
                    + fileName);
        }
    } /* End of method readFromFile */


    public void writeToFile(String fileName, ListInterface<User> userList) {
        try {
            /*
             * Create a FileWriter object that handles the low-level details of
             * writing
             */
            FileWriter theFile = new FileWriter(fileName);

            /* Create a PrintWriter object to wrap around the FileWriter object */
            /* This allows the use of high-level methods like println */
            PrintWriter fileOut = new PrintWriter(theFile);

            /* Print some lines to the file using the println method */
            for (int i = 1; i <= userList.size(); i++) {
                fileOut.println(userList.get(i).getUsername());
                fileOut.println(userList.get(i).getPassword());
            }
            /* Close the file so that it is no longer accessible to the program */
            fileOut.close();
        }

        /* Handle the exception thrown by the FileWriter methods */
        catch (IOException e) {
            System.out.println("Problem writing to the file");
        }
    } /* End of method writeToFile */
  • The userList is a dynamic linked list that uses generics (ListInterface<User>)

    if you dont want to use generics you could just say ListInterface userList, whereever it appears.

    • Your User class should implement the comparable and include the methods stated below:
    public int compareTo(User user) {
    
    }
    
    public boolean equals(Object user) {
    
    }
    
    • Note that, in case that you dont use generics, typecast might be needed. Otherwise, you will get compilation errors.



回答2:


When using String.split() it returns a String[] (Array) dividing it using the letters (regular expression) you send with it. You need to save it somewhere, otherwise split does nothing. So usrnm:username is sent back as an array of strings {"usrnm", username} using ":" as the parameter. So you just do:

    public void checkCredentials() {
    try {
        BufferedReader br = new BufferedReader(new FileReader(new File("accounts.txt")));
        String text = br.readLine();
        text = text.toLowerCase();
        String[] values = text.split(":");
        System.out.println(values[1]); // username is the second value in values
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

The you just do the same for next line from buffered reader, for the password.

Accounts.txt looking like this:

usrnm:USERNAME
pswrd:PASSWORD

in seperat lines for easy use with readline();



来源:https://stackoverflow.com/questions/20961522/how-to-read-a-specified-string-from-an-input-file-then-read-the-next-word-after

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!