编辑打开的文件后,如何保存更改?

时间:2014-07-21 05:25:21

标签: java swing file io jtextfield

我可以通过以下代码在文本字段txt1上打开文件。如何使用Buffered Reader或其他任何内容在同一功能的txt1字段中编辑后自动保存更改?

 private void btnOpenfileActionPerformed(java.awt.event.ActionEvent evt)                                            
{ 
 String file="";
  JFileChooser chooser = new JFileChooser("./");
    int i = chooser.showOpenDialog(null);
    if (i == 0) {
        File f = chooser.getSelectedFile();
        filelocation=f.getAbsolutePath();
    System.out.println(f); 

        try {
            FileReader fr = new FileReader(f); //file location passed
            BufferedReader br = new BufferedReader(fr);
            String temp = "";

                while ((temp = br.readLine()) != null) 
               {

               file += temp+"\n";

               }
            txt1.setText(file); //txt1 is a text field in split pane

            fr.close();
          } 
            catch (Exception e) 
           {
            System.out.println(e);
           }

}                                           

2 个答案:

答案 0 :(得分:3)

要在JTextComponent中加载和保存文字,请参阅read(Reader,Object)& write(Writer)

用于检测JTextField add an action listener的更改(通常在用户按下回车键时触发)或a DocumentListener

答案 1 :(得分:2)

您需要一个Writer和一个保存按钮或其他东西来触发保存操作:

    final BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(myFile));
    try
    {
        bufferedWriter.write(text);
    }
    catch (final IOException exception)
    {
        // Error handling.
    }
    finally
    {
        bufferedWriter.close();
    }