想法是这样的: 用户输入密码和登录数据,程序将它们写入文件。当您再次“注册”时,文件中的数据将被删除。我试图通过一个空字符串来实现它,但是由于无法关闭文件来保存它,因此新数据将覆盖旧数据。我无法执行此操作,因为存在“流关闭”错误。在案例2中,我关闭了第一个Writer。请看案例1。 有代码:
public class FL {
public static void main(String[] args) throws IOException {
String login, pass, name="User", admin="Administrator"; int a=0, k=0;
File LP = new File("LogPass.txt");
if (!LP.exists()) LP.createNewFile();
FileReader fr = new FileReader(LP);
FileWriter fw = new FileWriter(LP, true);
FileWriter reopen = new FileWriter(LP, false);
BufferedWriter reop = new BufferedWriter(reopen);
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
Scanner sc = new Scanner(System.in);
System.out.printf("Welcome!\n");
do {
System.out.println("Press 1 to Log In;\nPress 2 to Sign In;\nPress 3 to exit system.");
a = sc.nextInt();
switch (a) {
case 1:
reop.write("");//new login+password <<===== Here
reop.flush();
//reop.close();
System.out.println("Enter your Login: ");
sc.nextLine();
login = sc.nextLine();
bw.write(login);
System.out.println("Enter your Password: ");
pass = sc.nextLine();
bw.newLine();
bw.write(pass);
bw.flush();
break;
case 2:
bw.close();
System.out.println("Login: ");
sc.nextLine();
login = sc.nextLine();
if (login.equals(admin)) {
System.out.println("Login = "+br.readLine()+"\nPassword = "+br.readLine()); break;
}
System.out.println("Password: ");
pass = sc.nextLine();
name=login;
if (login.equals(br.readLine()) && pass.equals(br.readLine()))
System.out.println("You are in, "+name+"!"); else {
System.out.println("Invalid login or password..."); k++;
} if (k==3) {
System.out.println("You made the mistake three times in a roll - finishing work..."); System.exit(0);
}
break;
default: System.exit(0); break;
}
} while (a!=3);
}
}