关闭窗口时写入文件

时间:2013-12-20 10:17:11

标签: java user-interface

我正在写一个餐厅计划。 当用户确认他的订单时,订单存储在类型顺序的数组中。 为什么?因为当用户选择关闭程序时,所有订单都会保存在包含项目名称和每个项目信息的文件中。 此外,每个订单对象都有一个类型项数组!

你能帮我解决一下如何写这个文件吗? 我知道它将在方法processWindowEvent中。

这是我的尝试,我知道我应该删除 textArea.getText(),但我不知道如何打印所有项目。

  protected void processWindowEvent(WindowEvent e){

         if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            JOptionPane.showMessageDialog(this,"All operation have been saved ");

            try{
               outFile=new File("Orderslist.txt");
               out=new FileOutputStream(outFile);
               ob=new PrintWriter(out);}
               catch(IOException M){M.getMessage(); }
            for(int i=0;i<o2.length;i++){
               if(o2[i]!=null){
                  if(o2[i].getCount()<=4)
                     ob.println(o2[i].toString()+"\n--------------\n"+textArea.getText()+"--------------\n"+"\nTotal: "+o2[i].getTotalPrice());

                  else if(o2[i].getCount()>4)
                     ob.println(o2[i].toString()+"\n--------------\n"+textArea.getText()+"--------------\n"+"\nTotal Price#: "+o2[i].getTotalPrice()+"\n\nDiscount 20%\n\n--------------\nTotal price#: "+(o2[i].getTotalPrice()-(o2[i].getTotalPrice()*0.2)));

               }
            }

3 个答案:

答案 0 :(得分:0)

在Window的构造函数中添加:

public Window() {
    this.addWindowListener(new WindowAdapter(){
        @Override
        public void windowClosing(WindowEvent arg0) {
            writeFile(textArea.getText()); //Call your method
            System.exit(0);
        }
    });
    ...
}

用于编写文件:

File file = new File("myFile.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);

bw.write("Texto to write");
bw.close();

答案 1 :(得分:0)

ob.println()ob.close();ob.flush();

如果您不关闭流或刷新流,则文件中不会打印任何内容。

答案 2 :(得分:0)

实际上这不是最好的设计,你应该立即对文件进行更改。原因是如果应用程序由于任何其他原因(断电,任务管理器终止,崩溃等)而关闭,那么您不希望丢失用户的数据。还需要自动备份该文件(例如在启动后复制它),这样如果你以某种方式损坏了当前会话,你可以恢复。

要实际实现您想要使用某种类型的FileOutputStream的保存,但确切的实现会有很大的不同,具体取决于您希望流中的数据的格式。例如,XML,JSON,计划文本,二进制序列化等都非常简单,但您需要选择一个:)