【问题标题】:How to prevent the file to overwrite itself?如何防止文件覆盖自身?
【发布时间】:2015-04-09 14:06:50
【问题描述】:

我已经编辑了代码,你能告诉我如何在文件末尾写下每一行吗?这里写在同一行。你能帮忙吗?

private void okMouseClicked(java.awt.event.MouseEvent evt) {                                
    String pass = name.getText();
    if (pass.equals("")){
        error.setText("Name of Entity should not be left blank");
        //JOptionPane.showMessageDialog(null,"Name of Entity should not be left blank");
    }
    else{
        try{

            Formatter outfile = new Formatter(new FileOutputStream("Convert.sql", true));
            outfile.format("Create Database IF NOT EXISTS " + pass + ";");
            outfile.close();

        }

        catch(FileNotFoundException fnfe){
            System.out.println("Not found");

        }
        this.dispose();
    }
}

【问题讨论】:

  • 你要找的词是'overwrite',和SQL无关。 Swing 代码也没有。

标签: java java-io


【解决方案1】:

您可以将一个以追加模式创建的FileOutputStream 传递给Formatter 的构造函数:

Formatter outfile = new Formatter(new FileOutputStream("Convert.sql", true));
outfile.format("Create Database IF NOT EXISTS " + pass + ";\n");  // \n to add new line

http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.io.OutputStream)

【讨论】:

  • 感谢@manouti。但是如何在文件末尾添加每个语句而不是在同一行?
  • @LanaM 写入时只需添加换行符(\n):outfile.format("Create Database IF NOT EXISTS " + pass + ";\n");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 2014-05-26
  • 2015-09-09
相关资源
最近更新 更多