Link to home
Start Free TrialLog in
Avatar of lovely_rosa
lovely_rosa

asked on

Save File

I write simple editor using Jfram  ,  java GUI ,  one of the function is to open file  ,  when the user open the file  he or she want to edit the file  ,  then he \ she choose  save

the problem is here   , I want to save the opened file  on the same opened file  without asking me gain to choose name for the file

thankyou in advanced ,
 
for save action  I reuse this method  


class SaveAction extends AbstractAction {
    public SaveAction() {
      super("Save", new ImageIcon("icons/save.gif"));
    }

    // Query user for a filename and attempt to open and write the text
    // component's content to the file.
    public void actionPerformed(ActionEvent ev) {
      JFileChooser chooser = new JFileChooser();
      if (chooser.showSaveDialog(Main.this) != JFileChooser.APPROVE_OPTION)
        return;
      File file = chooser.getSelectedFile();
      if (file == null)
        return;

      FileWriter writer = null;
      try {
        writer = new FileWriter(file);
        textComp.write(writer);
      } catch (IOException ex) {
        JOptionPane.showMessageDialog(Main.this,
            "File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
      } finally {
        if (writer != null) {
          try {
            writer.close();
          } catch (IOException x) {
          }
        }
      }
    }
  }

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image

If you want to save to the same file you doen't need to use filechooser and don't need to instantite it
here. Do you have two button - one to save to the same file, another to "save as" ?
If you want to save to the same file from which you reda you should already tknow the file
so just removve this part

 JFileChooser chooser = new JFileChooser();
      if (chooser.showSaveDialog(Main.this) != JFileChooser.APPROVE_OPTION)
        return;
      File file = chooser.getSelectedFile();
      if (file == null)
        return;


and make sure you pass the File or filename to thios method,
You'll need to have this file closed and then opened again for wtriting

Avatar of lovely_rosa
lovely_rosa

ASKER

please I need more explain and thanks again for you
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I  did  it  thanks  a lot  

I  increase the point  for u