Java 如何读取文件以检查是否已创建用户名
因此,我正在创建一个名为RegisterandLogin的程序,基本上您必须输入用户名、密码并重新输入密码才能创建一个新帐户。 用户和密码的验证可通过以下方式完成: 1.您在注册期间键入的用户名不能与任何用户名相同 username.txt中的5个名称 2.此外,用户名必须介于5到8个字符之间,不带任何数字(即,用户名只能是[A-Z]或[A-Z],但不能是[0-9]之类的任何数字) 3.密码也在5到8个字符之间,允许数字(因此12345和abcde都是有效密码) 4.重新键入的密码必须与密码相同,否则,在点击注册按钮后会输出错误消息 当用户名通过5到8个字符的有效性检查时,用户名不存在 在username.txt中,如果密码通过有效性检查,则会添加新用户名 到username.txt 因此,我已经用五个名称创建了username.txt。但是,我的问题是我不知道如何读取username.txt文件,以便它可以检查用户名是否已被使用 代码在这里,有点长,任何帮助将不胜感激Java 如何读取文件以检查是否已创建用户名,java,Java,因此,我正在创建一个名为RegisterandLogin的程序,基本上您必须输入用户名、密码并重新输入密码才能创建一个新帐户。 用户和密码的验证可通过以下方式完成: 1.您在注册期间键入的用户名不能与任何用户名相同 username.txt中的5个名称 2.此外,用户名必须介于5到8个字符之间,不带任何数字(即,用户名只能是[A-Z]或[A-Z],但不能是[0-9]之类的任何数字) 3.密码也在5到8个字符之间,允许数字(因此12345和abcde都是有效密码) 4.重新键入的密码必须与密码相同
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);
}
}
import javax.swing.*;
导入java.io.*;
导入java.awt.event.*;
导入java.awt.*;
导入java.io.BufferedReader;
导入java.io.FileReader;
导入java.io.IOException;
导入java.io.*;
导入java.util.Scanner;
公共类RegisterandLogin扩展了JFrame{
//注册屏幕的变量
私人JPanel suP;
私人JLabel suName、suPW、suRetypePW;
私有JTextField suNameText、suPWText、suretypwtext;
私有JButton子按钮;
公共注册数据库()
{
超级(“注册和登录”);
在屏幕上签名();
}
屏幕上方的公共无效标志(){
suP=新JPanel();
//辅助设置尺寸(50、60);
setLayout(新的FlowLayout());
设置内容窗格(suP);
suName=新的JLabel(“名称”);
suNameText=新的JTextField(10);
suPW=新的JLabel(“密码”);
suPWText=新的JTextField(10);
suRetypePW=新的JLabel(“重新键入密码”);
suRetypePWText=新的JTextField(10);
子按钮=新的JButton(“寄存器”);
辅助添加(suName);
辅助添加(suNameText);
补充添加(补充);
辅助添加(辅助文本);
辅助添加(suRetypePW);
辅助添加(suRetypePWText);
辅助添加(子按钮);
辅助设置可见(真);
ButtonHandler handlersu=新ButtonHandler();
addActionListener(handlersu);
}
public void validatebyarray(){
字符串[]read1=null;
字符串[]读取=null;
read1=文件(已读);
int minL=5,maxL=8;
字符串stName=suNameText.getText();//用户名
字符串stPW=suPWText.getText();//密码
String stRePW=suRetypePWText.getText();//重新键入密码
/******************************************************
*验证用户名*
******************************************************/
if(stName.length()maxL)//检查用户名长度
System.out.println(“用户名必须介于5和8之间”);
其他的
{
//检查用户名中的无效字符
for(int i=0;i='A'&&stName.charAt(i)='A'&&stName.charAt(i)maxL)//检查用户名长度
System.out.println(“密码必须介于5和8之间”);
其他的
{
//检查用户名中的无效字符
for(int i=0;i ((stPW.charAt(i)>='0'&&stPW.charAt(i)='A'&&stPW.charAt(i)='A'&&stPW.charAt(i)您可以在阅读方法中执行以下操作
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()]);
}
公共字符串[]文件()
抛出FileNotFoundException
{
List existingUsers=new ArrayList();
文件用户=新文件(“username.txt”);
扫描仪sc=新扫描仪(用户);
while(sc.hasNext()){
existingUsers.add(sc.nextLine());
}
返回existingUsers.toArray(新字符串[existingUsers.size()]);
}
您可能已经尝试过使用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;
}
Map loadUsersAndPasswords(){
Map usernameToPassword=new HashMap();
FileReader fr=新的FileReader(“usernames.txt”);
试一试{
BufferedReader br=新的BufferedReader(fr);
对于(字符串line=br.readLine();line!=null;line=br.readLine()){
int splitLocation=line.indexOf(“:”);
字符串username=line.substring(0,splitLocation);
字符串密码=行.子字符串(拆分位置+1);
usernameToPassword.put(用户名、密码);
}
}最后{
fr.close();
}
返回usernameToPassword;
}
听起来像是家庭作业,你应该这样做。首先看一看,在问题或标题中说出来。缺少返回语句…还有你的电话