java gui - сохранение и загрузка данных - PullRequest
0 голосов
/ 22 сентября 2019

У меня есть класс библиотеки, который выглядит так:

public class Library implements Serializable{


    private static final long serialVersionUID = 1L;
    private static Library library; //a library
    private static Recommender recommender; //an instance of the recommender class
    private Set<LibraryItem> items; //set of library items
    private Set<Reader> readers; //set of readers
    private Set<Author> authors; //set of authors
    private Set<LibraryCollection> collections; //set of library collections
    private Set<Librarian> librarians; //set of the library librarians

Класс библиотеки - это класс Singelton.Я создаю графические окна для представления различных методов в классе, таких как добавление читателя в библиотеку.

В основном классе у меня есть этот код для сохранения и загрузки библиотеки:

public class MainClass implements Serializable{


    private static final long serialVersionUID = 1L;
    public static Library library;

    public static void main(String[] args)
    {
        try {
            library = loading();
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        if(library == null) {
            library = Library.getInstance();
        }
}
public static Library loading() throws IOException  //loading the system object
    {
        try
        {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("librery.srl"));
            library = (Library)in.readObject();
            JOptionPane.showMessageDialog(null,"Loading librery.ser file to the database", "Loading File", JOptionPane.INFORMATION_MESSAGE);
            return library;
        }

        //in case the file is not found
        catch (FileNotFoundException e)
        {
            JOptionPane.showMessageDialog(null,"File wasn't found, creating new library:", "Missing file", JOptionPane.ERROR_MESSAGE);
            return library;

        }

        //in case there was a problem loading data from file
        catch(IOException eio)
        {
            JOptionPane.showMessageDialog(null,"system wasn't able to read from file.. creating new library", "Read File Error", JOptionPane.INFORMATION_MESSAGE);
            return library;
        }

        //genreal exceptions
        catch (Exception e)
        {
            System.out.println(e.getMessage());
            return library;
        }
    }//end of loading method

    public static void save(Library library) throws IOException
    {
        //trying to save the data
        try
        { 
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("librery.srl"));
            out.writeObject(library);
            out.close();
        }

        //general exceptions
        catch (Exception e)
        { 
            JOptionPane.showMessageDialog(null,"Saving file was failed", "Save Error", JOptionPane.ERROR_MESSAGE);
        }
    }//end of save method

}

Я сохраняю библиотеку следующим образом:

public class SaveLibrary extends JFrame {

    private static final long serialVersionUID = 1L;

    public SaveLibrary() {
        super("Save Library");
JLabel lblDoYouWant = new JLabel("Do you want to save the library?");
        lblDoYouWant.setIcon(new ImageIcon("icons/icon.png"));
        lblDoYouWant.setBounds(0, 0, 434, 22);
        lblDoYouWant.setVerticalAlignment(SwingConstants.BOTTOM);
        lblDoYouWant.setHorizontalAlignment(SwingConstants.LEFT);
        lblDoYouWant.setFont(new Font("Tahoma", Font.BOLD, 18));
        lblDoYouWant.setBackground(new Color(216, 191, 216));
        getContentPane().add(lblDoYouWant);

        JRadioButton rdbtnYes = new JRadioButton("Yes");
        rdbtnYes.setIcon(new ImageIcon("icons/yes.png"));
        rdbtnYes.setHorizontalAlignment(SwingConstants.LEFT);
        rdbtnYes.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                //if the button is selected save the library and exit the program
                try {
                    MainClass.save(MainClass.library);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.exit(1);
            }
        });
        rdbtnYes.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 12));
        rdbtnYes.setBackground(new Color(216, 191, 216));
        rdbtnYes.setBounds(0, 48, 109, 23);
        getContentPane().add(rdbtnYes);
}

Когда я запускаю программу, она не сохраняет данные от одного запуска к другому.Что мне нужно изменить в методах сохранения и загрузки?Я просто не понимаю, почему это не работает.

1 Ответ

0 голосов
/ 22 сентября 2019

Если вы хотите сериализовать библиотеку, тогда Recommender, LibraryItem, ... тоже должны быть сериализуемыми.Чтобы контролировать сериализацию, рассмотрите возможность использования Externalizable вместо Serializable.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...