当我覆盖Application的stop()方法时,为什么我的文件没有被保存?

时间:2017-12-06 17:19:52

标签: java javafx jfilechooser filewriter bufferedwriter

我正在使用Javafx创建一个应用程序,并希望在应用程序关闭后保存数据。我重写了stop()方法,以便在单击关闭按钮后添加保存文件的功能。但是,当我查看文件时,它们是空的。关闭应用程序是否会自动清除我的代码中的所有信息,一旦调用save方法,我将不会保存任何内容?如果没有,为什么在我尝试填充它们之后我的文本文件是空的?感谢。

@Override
    public void stop() {
        try {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = chooser.showOpenDialog(null);
            File dir = null;
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                dir = chooser.getSelectedFile();
            }
            if (!dir.isDirectory()) {
                JOptionPane.showMessageDialog(null, "That directory does not exist.");
            }
            File file1 = new File(dir.getAbsolutePath() + "\\Titles.txt");
            FileWriter fw1 = new FileWriter(file1);  // saves titles
            BufferedWriter output1 = new BufferedWriter(fw1);
            for (int i = 0; i < titles.size(); i++) {
                output1.write(titles.get(i));
                output1.newLine();
            }
            output1.close();
            fw1.close();

            File file2 = new File(dir.getAbsolutePath() + "\\Formats.txt");
            FileWriter fw2 = new FileWriter(file2);  // saves formats
            BufferedWriter output2 = new BufferedWriter(fw2);
            for (int i = 0; i < formats.size(); i++) {
                output2.write(formats.get(i));
                output2.newLine();
            }
            output2.close();
            fw2.close();

            File file3 = new File(dir.getAbsolutePath() + "\\ListViewItems.txt");
            FileWriter fw3 = new FileWriter(file3);  // saves ListView items
            BufferedWriter output3 = new BufferedWriter(fw3);
            for (int i = 0; i < items.getItems().size(); i++) {
                output3.write(items.getItems().get(i));
                output3.newLine();
            }
            output3.close();
            fw3.close();


            File file4 = new File(dir.getAbsolutePath() + "\\Titles.txt");
            FileWriter fw4 = new FileWriter(file4);  // saves media items from Library Class
            BufferedWriter output4 = new BufferedWriter(fw4);
            for (int i = 0; i < lib.getItemList().size(); i++) {
                output4.write(lib.getItemList().get(i).toString());
                output4.newLine();
            }
            output4.close();
            fw4.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

0 个答案:

没有答案