如何覆盖现有文件Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27073951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:46:40  来源:igfitidea点击:

how to overwrite existing file Java

javasaveawtoverwritefiledialog

提问by Andhika Kurnia Aufa Azham

i want to overwriting file that i have saved before, my SaveAs code :

我想覆盖我之前保存的文件,我的 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?");
            }
        }

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.

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

采纳答案by Ehsan

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

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

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

Check out the constructor documentation:

查看构造函数文档