Java中非常简单的用户登录系统
我想用java做一个简单的登录系统,不使用数据库 我想这样做:Java中非常简单的用户登录系统,java,file-io,java.util.scanner,Java,File Io,Java.util.scanner,我想用java做一个简单的登录系统,不使用数据库 我想这样做: -1)I create a .txt file -2)put the username and password like this *user *pass *user *pass " " 是否可以使用扫描仪进行此操作?请帮忙,我只是个初学者 提前感谢创建类用户如下 class User implements Serializable { private String username; private
-1)I create a .txt file
-2)put the username and password like this
*user
*pass
*user
*pass
"
"
是否可以使用扫描仪进行此操作?请帮忙,我只是个初学者
提前感谢创建类
用户
如下
class User implements Serializable
{
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
创建可首次序列化到文件中的Hashmap
实例
private HashMap<String, User> hashMap = new HashMap<String, User>();
private HashMap HashMap=new HashMap();
使用此映射可根据用户名查找密码。您可以使用
BufferedWriter
包装输出流:
public static void main(String[] args) {
BufferedWriter writer = null;
try {
// create a BufferedWriter for the text file
writer = new BufferedWriter(new FileWriter("passwords.txt"));
// write text
writer.write("Tudor");
writer.newLine();
writer.write("Tudorspassword");
//etc.
} catch (IOException e) {
System.out.println("Failed to create file.");
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch (IOException e) {
System.out.println("Failed to close file.");
e.printStackTrace();
}
}
}
}
下面是如何阅读:
public static void main(String[] args) {
BufferedReader rdr = null;
try {
rdr = new BufferedReader(new FileReader("passwords.txt"));
String name = rdr.readLine();
String password = rdr.readLine();
while(name != null && password != null) {
System.out.println(name);
System.out.println(password);
name = rdr.readLine();
password = rdr.readLine();
}
} catch (FileNotFoundException e) {
System.out.println("Failed to open file.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Failed to correctly read file.");
e.printStackTrace();
} finally {
if(rdr != null) {
try {
rdr.close();
} catch (IOException e) {
System.out.println("Failed to close file.");
e.printStackTrace();
}
}
}
}
您必须使用
扫描仪吗
?我想先读取用户信息,然后读取通行证。好的,那么您需要阅读或写入文件的帮助吗?如果这是家庭作业,请放置标签。
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
/**
*
* @author Abhishek Banerjee
*/
public class NewMain {
public static void main(String[] args) throws IOException {
Scanner s1,s2;
s1=new Scanner(new FileInputStream("d:\\log.txt"));
s2=new Scanner(System.in);
boolean flag=false;
String name,pword,n,p;
System.out.println("Enter name:");
n=s2.next();
System.out.println("Enter password:");
p=s2.next();
while(s1.hasNext()) {
name=s1.next();
pword=s1.next();
if(n.equals(name) && p.equals(pword)) {
System.out.println("You are logged in.");
flag=true;
break;
}
}
if(!flag)
System.out.println("Incorrect password.");
}
}