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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16719019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:46:12  来源:igfitidea点击:

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

javaarrayssplitbufferedreaderreadline

提问by user2414384

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!!!

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.

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...

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]
  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...

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 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.

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.

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.

回答by Mena

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

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

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

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
  • 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.

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

Best of luck!

Best of luck!

回答by Menios

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).

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 hashmapthat takes a keyand a value.

For the specific case, you actually want a hashmapthat takes a keyand 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.

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

回答by Bob Stout

Declare your array outside the try/catch statement:

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.

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

回答by sanbhat

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

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 UserPOJO 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

I would recommend you to create a UserPOJO 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 ArrayListwhile parsing the file

and use ArrayListwhile 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)

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)