从.txt文件加载列表的程序将其保存回来

时间:2014-11-28 13:15:50

标签: java list export-to-text

所以基本上我有这段代码形成一个简单的JFrame程序,它将值(花名,LOL)存储到列表中并显示列表。但我只是无法弄清楚如何将列表保存到.txt文件并在启动时加载它...这可能是一个没脑子但我只是不明白,不知道从哪里开始< / p>

public class Flower extends JFrame implements ActionListener{

private List<String> flowerNames = new ArrayList<String>();


private JTextArea output;
private JTextField input;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run(){
            new Flower().setVisible(true);
        }
    });

}


public Flower() {
    setTitle("Flowers");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new GridLayout(1,2));
    JPanel right = new JPanel(new GridLayout(2,1));
    JPanel row = new JPanel();
    row.add(new JLabel("Flower: "));
    row.add(input = new JTextField(25));
    right.add(row);
    row = new JPanel();
    row.add(new JPanel(new FlowLayout()));
    JButton button = new JButton("Add");
    row.add(button);
    right.add(row);
    button.addActionListener(this);
    getContentPane().add(right);
    getContentPane().add(new JScrollPane(output = new JTextArea()));
    pack();
}

@Override
public void actionPerformed(ActionEvent arg0) {

    if (input.getText().length() > 0){
        try {
            flowerNames.add(input.getText());
        } catch (Exception e){
            JOptionPane.showMessageDialog(
                    this, 
                    "Wrong input!", 
                    "Check the input", 
                    JOptionPane.PLAIN_MESSAGE);

        }
        finally {
            Collections.sort(flowerNames);
            StringBuilder sb = new StringBuilder();
            for (String input : flowerNames){
                sb.append(input.toString() + "\n");
            }

            output.setText(sb.toString());
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

你应该从一开始 1)加载文件以填充Flower类的构造函数中的字符串列表花 2)然后在关闭操作上添加动作侦听器,而不是在关闭时添加默认出口,以便将列表保存为文件 3)最后你应该确保文件存在然后创建。