How to overwrite existing file? [duplicate]
Asked Answered
M

1

5

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.

Microspore answered 22/11, 2014 at 4:9 Comment(1)
i didnt find that question before. :) but thanksMicrospore
B
24

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:

Bette answered 22/11, 2014 at 4:16 Comment(1)
But won't that leave bits of the old file if the new file is smaller?Roux

© 2022 - 2024 — McMap. All rights reserved.