How to overwrite existing file?

50.7k views Asked by At

I want to overwriting file that I have saved before, my saveAs code:

public void saveAs(){
            judul = jTextJudul.getText();
            s = area.getText();
            if(s.length()>0){//jika s terisi
                try { 
                    dialog = new FileDialog(this,"Save File As",FileDialog.SAVE);
                    dialog.setFile(judul+".txt");
                    dialog.setVisible(true);
                    path=dialog.getDirectory()+dialog.getFile();
                    FileOutputStream fos=new FileOutputStream(path);
                    System.out.println(s);
                    byte[] b=s.getBytes();
                    fos.write(b);
                    fos.close();
                    setTitle(name);
                }
                catch(Exception e){
                    JOptionPane.showMessageDialog(this,e.getMessage());
                }
            }
            else{
                JOptionPane.showMessageDialog(this,"Apa anda yakin menyimpan file kosong?");
            }
        }

And my save code (that must be overwriting exist file)

public void Save(){
        dialog = new FileDialog(this,"Save",FileDialog.SAVE);
        file = new File(path+".txt");
        s = area.getText();
          try{
            // Create file 
            FileWriter fstream = new FileWriter(file,true);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(s);
            //Close the output stream
            out.close();
        }
        catch (IOException e){
            JOptionPane.showMessageDialog(this,e.getMessage());
        }
    }

But when I save, the file will saved to "null.txt"

This is not what I want. I would like to overwrite the file that i have saved before.

1

There are 1 answers

1
Ehsan On BEST ANSWER

Pass false as 2nd argument, to set append to false, so that you will overwrite the existing file:

FileOutputStream output = new FileOutputStream("output", false);

Check out the constructor documentation: