如何防止文件覆盖自身?

How to prevent the file to overwrite itself?

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

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

您可以将在附加模式下创建的 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)