Search code examples
javaswingfileiojtextfield

After editing opened file, how to save the changes?


I am able to open file through the code below on text field txt1. How can I save the changes automatically after editing in txt1 field in this same function by using Buffered Reader or anything else?

 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);
           }

}                                           

Solution

  • For loading and saving text in/from a JTextComponent, see read(Reader,Object) & write(Writer).

    For detecting changes to a JTextField add an action listener (that will typically fire when the user presses the enter key), or a DocumentListener.