Skip to content

Instantly share code, notes, and snippets.

@yassaa
Created November 17, 2014 10:49
Show Gist options
  • Save yassaa/e176dd4f46f76fb19e44 to your computer and use it in GitHub Desktop.
Save yassaa/e176dd4f46f76fb19e44 to your computer and use it in GitHub Desktop.
UserDatabase
package test_Bookingsystem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
public class UserDatabase {
// We use DataOutputStream and DataInputStream to save and load users to the harddisc, and use them in the
// program later
//save users to harddisc
public void saveUser(User user) {
try(DataOutputStream output = new DataOutputStream(new FileOutputStream("UserDatabase1.dat", true))){
output.writeUTF(user.getName());
output.writeUTF(user.getEmail());
output.writeLong(user.getPhonenumber());
}
catch (IOException ex) {
System.out.println(" error ");
}
}
// getUSer gets users from harddisc.....evt ændre til loadUser ?
public User[] getUsers () {
ArrayList<User> users = new ArrayList<User>();
try(DataInputStream input = new DataInputStream(new FileInputStream("UserDatabase1.dat"))){
String name = input.readUTF();
String email = input.readUTF();
long phoneNumber = input.readLong();
// add user to list
users.add(new User(name, email, phoneNumber));
}
//adding catch blocks
catch (IOException ex) {
//Reached end of stream. No more data to read
}
// returns the list as an array ( it converts a list of users to an array of users )
return users.toArray(new User[users.size()]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment