如何读取文件以检查是否已创建用户名

时间:2013-08-10 04:25:16

标签: java

所以我创建了一个名为RegisterandLogin的程序,基本上你必须输入用户名,密码和重新输入密码才能创建一个新帐户。 用户和密码的验证可以使用以下方式完成:

1.您在注册时输入的用户名不能与任何用户名相同 username.txt中的5个名字。

2.此外,用户名必须是5到8个字符,没有任何数字(即,用户名只能是[AZ]或[az],但不能是[0​​-9]之类的任何数字。)

3.密码也在5到8个字符之间,允许使用数字(因此12345和abcde都是有效密码)。

4.重新输入的密码必须与密码相同,否则在点击“注册”按钮后会输出错误信息。

当用户名通过5到8个字符的有效性检查时,用户名不存在 在username.txt中,密码通过有效性检查,添加新用户名 到username.txt。

所以我已经用五个名字创建了username.txt。但是,我遇到的问题是我不知道如何读取username.txt文件,以便检查用户名是否已被使用。

这里的代码,很长一段时间,任何帮助都会受到赞赏。

import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.*;
import java.util.Scanner;

public class RegisterandLogin extends JFrame  {


// variables for Sign up screen
private JPanel suP; 
private JLabel suName, suPW, suRetypePW;
private JTextField suNameText, suPWText, suRetypePWText;
private JButton suButton; 
public RegisterandLogin ()
    { 
    super ("Register and Login");
    signupScreen();

}

public void signupScreen () {
    suP = new JPanel ();
    // suP.setSize(50, 60);
    setLayout (new FlowLayout());
    setContentPane (suP);
    suName = new JLabel ("Name");
    suNameText = new JTextField (10);
    suPW = new JLabel ("Password");
    suPWText = new JTextField (10);
    suRetypePW = new JLabel ("Retype Password");
    suRetypePWText = new JTextField (10);
    suButton = new JButton ("Register");
    suP.add (suName);
    suP.add(suNameText);
    suP.add(suPW);
    suP.add (suPWText);
    suP.add (suRetypePW);
    suP.add (suRetypePWText);
    suP.add(suButton);
    suP.setVisible(true);
    ButtonHandler handlersu = new ButtonHandler();
    suButton.addActionListener(handlersu);
}

public void validatebyarray() {

    String[] read1=null;
            String[] read=null;
    read1=files(read);

    int minL = 5, maxL = 8;
    String stName = suNameText.getText();//username
    String stPW = suPWText.getText();//password
    String stRePW = suRetypePWText.getText();//retype password


    /******************************************************
     *  Validate user name                                   *
     ******************************************************/

    if(stName.length()< minL || stName.length() > maxL )  // Check username length
        System.out.println ("User name must be between 5 and 8");
    else 
    {
            //check invalid characters in username
        for (int i = 0 ; i < stName.length(); i ++)  // Check for invalid character
            if (!
               ((stName.charAt (i)>= 'A' && stName.charAt (i) <= 'Z') ||
               (stName.charAt (i)>= 'a' && stName.charAt (i) <= 'z')))
            {
                    System.out.println ("Username contains invalid character"); 
                    break;
            }

        // Match the names in the array (file or database)
        // Note the logic below works but is NOT secure since it discloses
        // information about user names.
        boolean uNfound = false;
        for (int j = 0; j < 4; j++)
            if (read1[j].equals(stName))
            {
                System.out.println ("User name " + read1[j] + " already exits");
                uNfound = true;
                break;
            }
        //if    (!uNfound)
        //  System.out.println ("User name " + stName + "  created");                       
    }
    System.out.println ("After UN");
    /******************************************************
     *  Validate password                                *
     ******************************************************/


    if(stPW.length()< minL || stPW.length() > maxL )  // Check username length
        System.out.println ("Password must be between 5 and 8");
    else 
    {
            //check invalid characters in username
        for (int i = 0 ; i < stPW.length(); i ++)  // Check for invalid character
            if (!
               ((stPW.charAt (i)>= '0' && stPW.charAt (i) <= '9') ||
                       (stPW.charAt (i)>= 'A' && stPW.charAt (i) <= 'Z') ||
                       (stPW.charAt (i)>= 'a' && stPW.charAt (i) <= 'z')))
            {
                    System.out.println ("Password contains invalid character"); 
                    break;
            }

        // Note stName replaced by stPW and stRePW;
        // uN[] replaced by pN[]
        boolean uNfound = false;

            if (stPW.equals(stRePW))
            {
                System.out.println ("User name " + stName + "  created");
                uNfound = true;

            }
        if  (!uNfound)
            System.out.println ("Passwords does not match");







}
    //System.out.println ("After UN again");
}





class ButtonHandler implements ActionListener
{
    public void actionPerformed (ActionEvent event){

        if (event.getSource () == suButton){
            System.out.println ("SU button in register screen hit");

            validatebyarray();
        }
    }
}

public String[] files(String [] read) 
{
    try {



        BufferedReader file1 = new BufferedReader(new FileReader("usernames.txt"));                   
        //  Scanner fileReaderScan=new Scanner(readTextFile);

            //only want first 5 lines
            for(int count=0;count<5;count++)
            {
               read[count] = file1.readLine();  //use readLine method
           System.out.println(read[count]);
            }

       file1.close();   //close file

    }


    catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("OOps");
    }
    return read;
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
RegisterandLogin rl = new RegisterandLogin ();
rl.setSize(200, 300);
rl.setVisible(true);
rl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

2 个答案:

答案 0 :(得分:1)

您可以在阅读方法

中执行以下操作
public String[] files() 
    throws FileNotFoundException
{
   List<String> existingUsers = new ArrayList<String>();
   File users = new File("username.txt");
   Scanner sc = new Scanner(users);
   while (sc.hasNext()) {
       existingUsers.add(sc.nextLine());
   }
   return existingUsers.toArray(new String[existingUsers.size()]);
 }

答案 1 :(得分:0)

你可能只是尝试使用BufferedReader,但你在编写的代码中已经硬编码了要读取的行数,但问题是关于在文件中附加行。

我想你也希望文件包含密码(这是家庭作业,在现实生活中你永远不会存储密码),因为大概你最终会以某种方式检查它们。鉴于您必须对合法字符施加限制,您可以轻松选择一个分隔符,以便在文件中每行存储用户名和密码。

由于您的使用模式是您需要有效地检查存在,因此用于用户名的更好的数据结构将是一个集合,给定的密码也不是您想要的密码,从用户名到密码的映射将是一个不错的选择

使用资源(例如文件)时,最好使用finally块关闭它们,这样无论出现什么问题,都可以释放对资源的使用。

所以你最终会得到类似......

Map<String,String> loadUsersAndPasswords() {
    Map<String,String> usernameToPassword = new HashMap<String,String>();
    FileReader fr = new FileReader("usernames.txt");
    try {
        BufferedReader br = new BufferedReader(fr);
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            int splitLocation = line.indexOf(":");
            String username = line.substring(0, splitLocation);
            String password = line.substring(splitLocation + 1);
            usernameToPassword.put(username, password);
        }
    } finally {
        fr.close();
    }

    return usernameToPassword;
}