-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAccountManager.java
53 lines (47 loc) · 1.56 KB
/
AccountManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package server;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class AccountManager {
static HashMap<String, String> users = new HashMap<>();
static String fileName = "users.txt";
public static void loadFromFile() {
users.clear();
try {
File file = new File(fileName);
if(!file.exists())
saveToFile();
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
StringBuilder in = new StringBuilder(reader.nextLine());
if(!in.toString().equals("")) {
String trimmed = in.substring(1, in.length()-1);
StringTokenizer tokenizer = new StringTokenizer(trimmed, ", ");
String username = tokenizer.nextToken();
String password = tokenizer.nextToken();
users.put(username, password);
}
}
reader.close();
} catch (FileNotFoundException exception) {
System.out.printf("[Error] Unable to Read %s!\n", fileName);
}
}
public static void saveToFile() {
try {
File file = new File(fileName);
file.createNewFile(); // Safe to run, doesn't override existing file.
FileWriter writer = new FileWriter(fileName);
for(String user : users.keySet()) {
writer.write(String.format("(%s, %s)\n", user, users.get(user)));
}
writer.close();
} catch (IOException exception) {
System.out.printf("[Error] Unable to Write %s!\n", fileName);
}
}
}