шпаргалки
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.1 KiB

2 years ago
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package propertiesswing2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author denis
*/
public class PersonStore {
private static Set<User> persons = new HashSet<>();
private static PersonStore personStore;
private File file;
private PersonStore(){
file = new File("persons.txt");
if(!file.exists()) try {
file.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}else readStore();
}
public static PersonStore getPersonStore(){
if (personStore == null) personStore = new PersonStore();
return personStore;
}
public void addUser(User user){
persons.add(user);
saveStore();
}
public HashSet<User> getPersons(){
return new HashSet<>(persons);
}
private void readStore(){
if(file==null || !file.canRead()) return;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
Object result = ois.readObject();
persons = result!=null ? (HashSet<User>)result : new HashSet<>();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void saveStore(){
if(file==null || !file.canRead()) return;
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
oos.writeObject(persons);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}