如何覆盖现有的Java文件

时间:2014-11-22 04:09:28

标签: java save awt overwrite filedialog

我想覆盖我以前保存的文件,我的SaveAs代码:

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

我的保存代码(必须覆盖存在的文件)

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

但是当我保存时,文件将保存为“null.txt” 这不是我想要的。我想覆盖之前保存过的文件。

1 个答案:

答案 0 :(得分:21)

将false作为第二个参数传递,将append设置为false,以便覆盖现有文件:

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

查看构造函数documentation