how to overwrite existing file Java

Andhika Kurnia Aufa Azham picture Andhika Kurnia Aufa Azham · Nov 22, 2014 · Viewed 48k times · Source

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.

Answer

Ehsan picture Ehsan · Nov 22, 2014

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: