1 回答

TA貢獻1848條經(jīng)驗 獲得超10個贊
這不是您與數(shù)據(jù)庫交互的方式。編寫一個User類來存儲用戶名和密碼。然后編寫一個數(shù)據(jù)庫類來讀取文本文件并創(chuàng)建 User 對象的 ArrayList。然后使用 User.name 進行搜索,并在登錄前檢查 User.password 進行驗證。
數(shù)據(jù)庫會將文本文件中的數(shù)據(jù)“加載”到 ArrayList 中,這將是您的程序?qū)⑴c之交互的內(nèi)容。如果您想重寫文本文件,請編寫一個保存函數(shù)來清除并打印到相關(guān)文件。
這是一個數(shù)據(jù)庫類的示例(來自我的一個舊項目),它以以下格式讀取學生的數(shù)據(jù): name:HARSH|PID:12|major:null|minor:null|CGPA:4.100000|college:null|email:abcd@gmail.com
import java.util.*;
import java.text.*;
import java.time.*;
import java.io.*;
public class Database{
public List<Student> studentList;
private long lastModified;
@SuppressWarnings("unchecked")
public Object loadDb()
{//Loads the database from file.
File data = new File("database.db");
if(lastModified == data.lastModified())
{
return studentList;//Returning main memory;
}
Scanner sc;
try
{
sc = new Scanner(data).useDelimiter("\n");//To get individual lines.
String line;
if(studentList!=null)
{//Clearing main memory.
studentList.clear();
}
else
{//Creating new main memory.
studentList = new ArrayList<Student>();
}
while(sc.hasNext())
{
line = sc.next();
Scanner l = new Scanner(line).useDelimiter("\\|");//To get info
String name, PID, major, minor, cgpaSt, college, email;
name = l.next().split(":")[1];
PID = l.next().split(":")[1];
major = l.next().split(":")[1];
minor = l.next().split(":")[1];
cgpaSt = l.next().split(":")[1];
college = l.next().split(":")[1];
email = l.next().split(":")[1];
double CGPA = Double.valueOf(cgpaSt);
Student stud = new Student(name,PID, major, minor, CGPA, college, email);//Creating new student with same info.
studentList.add(stud);//Adding the student to memory.
}
sc.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return studentList;
}
@SuppressWarnings("unchecked")
public void updateDb(Object studList)
{//Updates the database.
File data = new File("database.db");
PrintWriter fs;
try
{
fs = new PrintWriter(data);
}
catch(IOException e)
{
System.out.println("IO Exception!");
return;
}
fs.flush();
ArrayList<Student>studs = (ArrayList<Student>)studList;
for(int i = 0;i<studs.size();i++)
{
fs.print(studs.get(i).toString());
if(i != studs.size() -1)
{
fs.print("\n");
}
}
fs.close();
lastModified = data.lastModified();
loadDb();//Loading updated database.
}
}
您必須toString()為您的用戶類編寫一個函數(shù),并根據(jù)您的格式修改讀數(shù)。Database userData = new Database();這將允許您在中心類中創(chuàng)建一個變量。然后,您可以與studentList(在您的例子中為userList)交互,并搜索該用戶,然后檢查他們的密碼是否正確。
添加回答
舉報