简体   繁体   中英

read from a file, split the line and store in an array JAVA

Okay guys first and foremost let me say that I am a NOVICE when it comes to programming in JAVA. I am teaching myself, so with that said please bear with me as I am doing the best I can with what I have. With that said, here is my dilemma!!!

I have a file "Users.csv" that stores username and password fields.

username,password
josh,123456ABC
bman,turtlestew123
etc...

What I am trying to do is...

  1. Read the lines from this document (Users.csv) (which is in the same directory as the class file)
  2. Split the lines using .split(","); on the input
  3. Store split 1 in an array[0] and split 2 in the same array[1]

The array must be able to grow as I add users to the file. Eventually I will want to verify information from the array but my main concern right now is how to even get the information into the array. Here is what I am playing around with, but I don't know how to make it do what I want...

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BufferedReaderExample {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader("Users.csv")))
        {

            String sCurrentLine;
            String first = "Username is: ";
            String second = "Password is: ";

            while ((sCurrentLine = br.readLine()) != null) {


                String[] information = sCurrentLine.split(",");
                String username = information[0];
                String password = information[1];
                System.out.println(username);
                System.out.println(password);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } 

    }
}

This code will read the lines, and will split them and output them to the screen... but it isn't storing them in the array, so I cant use the array to look for specific elements.

This is for a login gui. simple username and password fields. When the person hits the logon button, I want it to pull the information from the file, check the username and then verify their password. Again this part is the big picture but just wanting to let you know what it is being used for.

Also, please remember that I am very inexperienced and if you post code please don't use something similar but different as that just confuses me even more.

I think your array is not growing because you are re-declaring for each line of your file (it's in the while loop). To fix that, you could initialize your array before the loop, and use System.arraycopy to make it grow.

A part from this quick fix, there is a number of problems with your idea in my opinion:

  • Usernames and passwords should not be stored in a csv file, rather in a database
  • Passwords should be hashed and never be visible in clear from the application itself
  • The database should be salted
  • An array is not the correct data structure to represent key value pairs - you should use a Map for that
  • In the occurrence, getting all the usernames/passwords in memory to compare them with a user login is not reasonable. You should hash the pwd provided by the user, find the username in the database, and compare the two hashes

I'm simplifying a bit here, there are tons of literature about that.

Best of luck!

Usually people use an ArrayList for this as apposed to an Array. An array required knowing total number of elements, while an arraylist uses an array underneath and dynamically resizes if necessary (well, creates a bigger array and copies data over).

For the specific case, you actually want a hashmap that takes a key and a value .

   import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;

public class BufferedReaderExample {

public static void main(String[] args) {



           try (BufferedReader br = new BufferedReader(new FileReader("Users.csv")))
            {

                String sCurrentLine;
                String first = "Username is: ";
                String second = "Password is: ";
                java.util.HashMap<String,String> data = new java.util.HashMap<String,String>();


                while ((sCurrentLine = br.readLine()) != null) {       
                    String[] information = sCurrentLine.split(",");
                    String username = information[0];
                    String password = information[1];
                    System.out.println(username);
                    System.out.println(password);
                    data.put(username,password);
                    }

            } catch (IOException e) {
                e.printStackTrace();
            } 

        }
    }

When a login comes, you use data.get(username); to get the stored password, and compare with what the user has given.

Declare your array outside the try/catch statement:

    String[] information;
    try (BufferedReader br = new BufferedReader(new FileReader("Users.csv")))
    {

        String sCurrentLine;
        String first = "Username is: ";
        String second = "Password is: ";

        while ((sCurrentLine = br.readLine()) != null) {


            information = sCurrentLine.split(",");
            String username = information[0];
            String password = information[1];
            System.out.println(username);
            System.out.println(password);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

Then, you'll be able to use the data generated elsewhere.

If you want auto-increment array, Use ArrayList . These are special data structures which increase as the items get added to them.

I would recommend you to create a User POJO class , because tomorrow, if one more property gets added to the rows of CSV, it can be adopted by adding one more field in the below class

class User {

   private String userName;
   private String password;
   //getter :setters

}

and use ArrayList while parsing the file

List<User> userList = new ArrayList<User>();
try (BufferedReader br = new BufferedReader(new FileReader("Users.csv")))
        {

            String sCurrentLine;
            String first = "Username is: ";
            String second = "Password is: ";

            while ((sCurrentLine = br.readLine()) != null) {


                String[] information = sCurrentLine.split(",");
                String username = information[0];
                String password = information[1];

                User u = new User(); 
                u.setUserName(username);
                u.setPassword(password);
                userList.add(u);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } 
}

ALSO: Storing the user's password in a csv file is a security risk. Try using database and store encrypted passwords instead of actual password (while retrieving just decrypt the password and compare)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM