我想在不使用数据库的情况下在 java 中制作一个简单的登录系统。(PS。没有敏感数据)我想做这样的事情:
-1)I create a .txt file
-2)put the username and password like this
*user
*pass
*user
*pass
"
"
是否可以使用扫描仪做到这一点?请帮忙,因为我只是一个初学者
提前致谢
我想在不使用数据库的情况下在 java 中制作一个简单的登录系统。(PS。没有敏感数据)我想做这样的事情:
-1)I create a .txt file
-2)put the username and password like this
*user
*pass
*user
*pass
"
"
是否可以使用扫描仪做到这一点?请帮忙,因为我只是一个初学者
提前致谢
您可以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.");
}
}
创建User
如下所示的类
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>();
使用此映射以根据用户名查找密码。