2015-02-09 90 views
3

我编辑了代码,你能告诉我如何在文件末尾写出每行吗?这里写的是同一行。你能帮忙吗?如何防止文件覆盖自身?

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

你正在寻找的词是'覆盖',而SQL与它无关。 Swing代码也没有。 – EJP 2015-02-09 21:12:46

回答

0

可以传递到Formatter以附加模式创造了一个FileOutputStream构造:

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)

+0

感谢它的工作@ manouti。但是我怎样才能在文件末尾添加每条语句,而不是在同一行? – Lana 2015-02-09 19:13:23

+0

@LanaM写入时只需添加一个换行符('\ n'):'outfile.format(“创建数据库IF NOT EXISTS”+ pass +“; \ n”);' – manouti 2015-02-09 19:25:12