2011-10-06 53 views
2

我有写入文件中的以下功能:写入一个文本文件,在java中

public void writeToFile(String data) throws IOException { 
    FileWriter fstream = null; 


    try { 
     fstream = new FileWriter("out.txt"); 
     BufferedWriter out = new BufferedWriter(fstream); 
     out.write(data); 
     //Close the output stream 
     out.close(); 
    } catch (IOException ex) { 
     Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex); 
    } finally { 
     try { 
      fstream.close(); 
     } catch (IOException ex) { 
      Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
} 

它能做什么每次调用它会创建一个新的文件,并写入一个新行时间。我想要实现的是检查文件是否存在。如果不创建一个新文件并写入一些内容,如果存在,则打开该文件并添加一个新行,而不删除现有文本。怎么做?

+0

ISFILE(指定:Java文档中)如果文件存在则返回true,否则返回false。 – Waltzy

+0

或者自己保存一些代码:'com.google.common.io.Files.append(CharSequence,File,Charset)' – artbristol

回答

6

改变你的FileOutputStream中的构造函数调用此:

fstream = new FileWriter("out.txt", true); 
2

的FileWriter需要在附加额外的参数,如果你想创建一个新的文件或附加到现有的文件

fstream = new FileWriter("out.txt", true); 

http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean

+1

+1,无法理解为什么其他答案有更多的投票,这是一个更好的答案,尽管链接可能会更好,因为http://download.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean) – Qwerky