1
- import java .io .File ;
2
- import java .io .FileNotFoundException ;
3
- import java .io .PrintWriter ;
1
+ import java .io .*;
4
2
import java .util .Scanner ;
5
3
public class UserDatabase implements UserExists , UserCreator {
6
4
File accounts ;
@@ -9,31 +7,40 @@ public UserDatabase(File accounts){
9
7
}
10
8
@ Override
11
9
public boolean UserExists (String username , String email ) {
12
- try (Scanner x = new Scanner (this .accounts )){
13
- x .useDelimiter ("\n " );
14
- while (x .hasNext ()) {
15
- String [] y = x .next ().split ("," );
16
- if (y [0 ].equals (username ) || y [2 ].equals (email )){
17
- return true ;
10
+ User user = null ;
11
+ try (FileInputStream fileIn = new FileInputStream (accounts );
12
+ ObjectInputStream in = new ObjectInputStream (fileIn )){
13
+ do {
14
+ try {
15
+ user = (User )in .readObject ();
16
+ }catch (NullPointerException e ){
17
+ break ;
18
18
}
19
- }
20
- }catch (FileNotFoundException e ){
21
- System .out .println ("Cannot find File" );
22
- };
23
- return false ;
19
+ }while (!user .getEmail ().equals (email ) && !user .getUsername ().equals (username ));
20
+ }catch (IOException e ){
21
+ e .printStackTrace ();
22
+ } catch (ClassNotFoundException e ) {
23
+ throw new RuntimeException (e );
24
+ }
25
+ return user != null ;
24
26
}
25
27
26
28
// Creates a new user with a username and password, and an email address
27
29
// The order is username, password, email address, verification status, status
28
30
//
29
31
@ Override
30
- public void createUser (String username , String password , String email ) {
31
- try (PrintWriter out = new PrintWriter (this .accounts )){
32
- out .println (username + "," + password + "," + email + "," + "no" + "," + "offline" );
33
- out .flush ();
34
- }catch (FileNotFoundException e ){
35
- System .out .println ("Error creating/writing to file" );
36
- e .printStackTrace ();
37
- };
32
+ public void createUser (String username , String password , String email ){
33
+ User newUser = new User (username , password , email );
34
+ try (FileOutputStream fileOut = new FileOutputStream (accounts )){
35
+ try (ObjectOutputStream out = new ObjectOutputStream (fileOut )){
36
+ out .writeObject (newUser );
37
+ out .close ();
38
+ fileOut .close ();
39
+ }catch (Exception e ){
40
+ System .out .println ("Error" );
41
+ }
42
+ }catch (Exception e ){
43
+ System .out .println ("Error" );
44
+ }
38
45
}
39
46
}
0 commit comments