【问题标题】:How to overwrite existing file? [duplicate]如何覆盖现有文件? [复制]
【发布时间】:2015-01-20 08:12:38
【问题描述】:

我想覆盖我之前保存的文件,我的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”

这不是我想要的。我想覆盖我之前保存的文件。

【问题讨论】:

  • 我之前没有发现这个问题。 :) 但是谢谢

标签: java save awt overwrite filedialog


【解决方案1】:

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

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

查看构造函数documentation:

【讨论】:

  • 但是如果新文件更小,那不会留下旧文件的一部分吗?
猜你喜欢
  • 2013-10-10
  • 1970-01-01
  • 2014-08-13
  • 2015-09-07
  • 2014-03-14
  • 2021-11-27
  • 1970-01-01
  • 2016-04-22
  • 2015-01-03
相关资源
最近更新 更多