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.
77 lines
2.4 KiB
77 lines
2.4 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 propertiesswing;
|
||
|
|
||
|
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.ArrayList;
|
||
|
import java.util.Collections;
|
||
|
import java.util.HashSet;
|
||
|
import java.util.List;
|
||
|
import java.util.Set;
|
||
|
import java.util.logging.Level;
|
||
|
import java.util.logging.Logger;
|
||
|
|
||
|
/**
|
||
|
*
|
||
|
* @author denis
|
||
|
*/
|
||
|
public final class PersonStore {
|
||
|
private static Set<Person> 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) {
|
||
|
Logger.getLogger(PropertiesSwing.class.getName()).log(Level.SEVERE, null, ex);
|
||
|
}
|
||
|
readStore();
|
||
|
}
|
||
|
|
||
|
public static PersonStore getPersonStore(){
|
||
|
if (personStore == null) personStore = new PersonStore();
|
||
|
return personStore;
|
||
|
}
|
||
|
|
||
|
public void addPerson(Person person){
|
||
|
persons.add(person);
|
||
|
saveStore();
|
||
|
}
|
||
|
|
||
|
public HashSet<Person> 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<Person>)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) {
|
||
|
Logger.getLogger(PropertiesSwing.class.getName()).log(Level.SEVERE, null, ex);
|
||
|
} catch (IOException ex) {
|
||
|
Logger.getLogger(PropertiesSwing.class.getName()).log(Level.SEVERE, null, ex);
|
||
|
}
|
||
|
}
|
||
|
}
|