这是主要方法及其类:
import java.util.*;
public class TestWithCLI {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String command = null;
do {
System.out.print(">");
try {
command = in.nextLine();
switch (command){
case "add user":
System.out.println("Enter the email then the password of the user you wish to add:");
System.out.println(DatabaseManager.addNewUser(new User(in.nextLine(), in.nextLine(), 0)));
break;
case "restore":
System.out.println(DatabaseManager.restore());
break;
case "exit":
break;
default:
System.out.println("Please enter a valid command.");
break;
}
}
catch (Exception e){
System.out.println("An error has been thrown.");
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println();
} while (!command.equals("exit"));
}
}
这是restore()方法,它返回一个成功的布尔值:
public static boolean restore() {
try {
Scanner in = new Scanner(System.in);
System.out.print("Are you sure you want to delete the changes made to the database since the last backup? [y/n]\n>");
if (in.nextLine().equals("y")){
BufferedReader br = new BufferedReader(new FileReader(backup));
BufferedWriter bw = new BufferedWriter(new FileWriter(db));
String line = br.readLine();
while (line != null){
bw.write(line);
bw.newLine();
line = br.readLine();
}
bw.close();
br.close();
in.close();
return true;
}
else {
in.close();
return false;
}
}
catch (Exception e){
return false;
}
}
每当我打电话给DatabaseManager.restore()
时,我都会遇到无穷无尽的错误。这是它在无限循环中打印的内容:
>An error has been thrown.
No line found
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at database.TestWithCLI.main(TestWithCLI.java:9)
我瞥见了#34; true"在错误向地平线滚动之前,我知道restore()正确执行,因为确实恢复了数据库文件。 "添加用户"命令也很好。