而不是重写新文件被创建

时间:2013-07-09 08:48:43

标签: java

我正在尝试写入已存在的文件。据我在论坛上看到,这段代码应该重写旧文件,但不是重写,而是将文件名放入[]括号中并创建一个新文件。有什么想法吗?

 try {
   File file = new File("/home/erik/glassfish3/" + selectedMss + ".ini");
   BufferedWriter output = new BufferedWriter(new FileWriter(file));
   for (String newline : content) {
     output.write(newline + "\n");
   }
   output.close();
 } catch (IOException e) {
   e.printStackTrace();
 }

2 个答案:

答案 0 :(得分:5)

FileWriter类有一个构造函数,它接受第二个布尔参数,该参数指定编写器是否应该使用追加模式,该模式会将新内容附加到现有文件的末尾。

我还建议在finally块中关闭作者。

Documentation

BufferedWriter output;
try {                
    File file = new File("/home/erik/glassfish3/"+selectedMss+".ini");

    //Providing true for second argument specifies it should be appended. 
    output = new BufferedWriter(new FileWriter(file,true));

    for(String newline: content){
        output.write(newline+"\n");      
    }

} catch ( IOException e ) {
       e.printStackTrace();
}finally{
  output.close();
}

答案 1 :(得分:2)

试试这个:

    try 
    {
           File file = new File("/home/erik/glassfish3/" + selectedMss + ".ini");
           BufferedWriter output = new BufferedWriter(new FileWriter(file,false));
            //true to append       //false to overwrite.

           for (String newline : content) 
           {
                  output.write(newline + "\n");
           }
           output.close();
           catch (IOException e)
           {
                  e.printStackTrace();
           }
    }

您还可以查看java文档以获得更多说明:

http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html