This is the main method and its class:
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"));
}
}
And this is the restore() method, it returns a boolean for success:
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;
}
}
Whenever I call DatabaseManager.restore()
I get an endless thread of errors. This is what it prints, on an infinite loop:
>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)
I caught a glimpse of "true" before the errors scroll off towards the horizon, and I know restore() executes properly because the database file is indeed restored. The "add user" command works perfectly fine, too.