现在想往一个txt文件里面不停的去追加数据,用new File(path)去操作,但是每次执行的时候这个文件都会被重新创建(该文件存在的时候也是如此),怎样操作才不会重复创建文件??

解决方案 »

  1.   

    http://hi.baidu.com/badlucktang/blog/item/27251c00f65cf609728da5e4.html
    // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件  
     FileWriter writer = new FileWriter(fileName, true);  
      

  2.   

    FileWriter writer = new FileWriter(fileName, true);   
      

  3.   

    file.exists()? 
    true:打开文件
    false:创建文件
      

  4.   


    FileOutputStream
    public FileOutputStream(String name,
                            boolean append)
                     throws FileNotFoundException
    Creates an output file stream to write to the file with the specified name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection. 
    First, if there is a security manager, its checkWrite method is called with name as its argument. If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown. 
    Parameters:
    name - the system-dependent file name
    append - if true, then bytes will be written to the end of the file rather than the beginning 
    Throws: 
    FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason. 
    SecurityException - if a security manager exists and its checkWrite method denies write access to the file.
    Since: 
    JDK1.1 
    See Also:
    SecurityManager.checkWrite(java.lang.String)
      

  5.   

    FileOutputStream
    public FileOutputStream(String name,
                            boolean append)
                     throws FileNotFoundException创建一个向具有指定 name 的文件中写入数据的输出文件流。如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。创建一个新 FileDescriptor 对象来表示此文件连接。 
    首先,如果有安全管理器,则用 name 作为参数调用 checkWrite 方法。 如果该文件存在,但它是一个目录,而不是一个常规文件;或者该文件不存在,但无法创建它;抑或因为其他某些原因而无法打开它,则抛出 FileNotFoundException。 
    参数:
    name - 与系统有关的文件名
    append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处 
    抛出: 
    FileNotFoundException - 如果该文件存在,但它是一个目录,而不是一个常规文件;或者该文件不存在,但无法创建它;抑或因为其他某些原因而无法打开它。 
    SecurityException - 如果存在安全管理器,且其 checkWrite 方法拒绝对文件进行写入访问。
    从以下版本开始: 
    JDK1.1 
    另请参见:
    SecurityManager.checkWrite(java.lang.String)