4
4
public class UserDatabase implements UserExists , UserRetriever , UserCreator , IRetrieveList {
5
5
File accounts ;
6
6
List <User > accountList ;
7
+ public UserDatabase (){
8
+ this .accounts = new File ("TestUserDatabase3.csv" );
9
+ this .accountList = this .getList ();
10
+ }
7
11
public UserDatabase (File accounts ){
12
+ if (!accounts .exists ()){
13
+ try {
14
+ accounts .createNewFile ();
15
+ } catch (IOException e ) {
16
+ throw new RuntimeException (e );
17
+ }
18
+ }
8
19
this .accounts = accounts ;
9
20
this .accountList = this .getList ();
10
21
}
11
22
@ Override
12
23
public boolean UserExists (String username , String email ) {
13
- /*User user = null;
14
- try(FileInputStream fileIn = new FileInputStream(accounts);
15
- ObjectInputStream in = new ObjectInputStream(fileIn)){
16
- do{
17
- try{
18
- user = (User)in.readObject();
19
- }catch(NullPointerException e){
20
- user = null;
21
- break;
22
- }
23
- }while(!user.getEmail().equals(email) && !user.getUsername().equals(username));
24
- }catch(IOException e){
25
- e.printStackTrace();
26
- } catch (ClassNotFoundException e) {
27
- throw new RuntimeException(e);
28
- }
29
- return user != null;*/
30
24
for (User user : this .accountList ){
31
25
if (user .getUsername ().equals (username ) || user .getEmail ().equals (email )){
32
26
return true ;
@@ -41,10 +35,10 @@ public boolean UserExists(String username, String email) {
41
35
@ Override
42
36
public void createUser (String username , String password , String email , String type ){
43
37
User newUser = UserFactory .BirthUser (username , password , email , type );
38
+ this .accountList .add (newUser );
44
39
try (FileOutputStream fileOut = new FileOutputStream (accounts )){
45
40
try (ObjectOutputStream out = new ObjectOutputStream (fileOut )){
46
- out .writeObject (newUser );
47
- this .accountList .add (newUser );
41
+ out .writeObject (this .accountList );
48
42
out .close ();
49
43
fileOut .close ();
50
44
}catch (Exception e ){
@@ -72,19 +66,22 @@ public User getUser(String username) {
72
66
public List <User > getList () {
73
67
List <User > users = new ArrayList <>();
74
68
try (FileInputStream fileIn = new FileInputStream (accounts );
75
- ObjectInputStream in = new ObjectInputStream (fileIn )){
76
- /*User user = (User) in.readObject();*/
69
+ ObjectInputStream in = new ObjectInputStream (fileIn )) {
70
+
71
+ users = (ArrayList <User >) in .readObject ();
72
+ /*
77
73
while(true){
78
74
try{
79
75
User user = (User) in.readObject();
80
76
users.add(user);}
81
77
catch(EOFException e){
82
78
break;
83
- }
84
- }
85
- }catch (Exception e ){
86
- e .printStackTrace ();
79
+ }*/
80
+ return users ;
81
+ }catch (EOFException e ){
82
+ return users ;
83
+ } catch (IOException | ClassNotFoundException ex ) {
84
+ throw new RuntimeException (ex );
87
85
}
88
- return users ;
89
86
}
90
87
}
0 commit comments