FileWriter false将文件从字符串A覆盖到Z BUT只留下字符串Z;如何保持字符串A-Z?

时间:2013-05-05 02:29:20

标签: java append filewriter

所以我的程序中有以下代码。我要做的是将我在程序主程序中声明的变量打印到csv文件。我想替换csv文件中已经存在的内容(在我们到达这部分代码之前文件存在,所以我们要做的就是替换已经存在的内容)。现在,我尝试了(myFoo,false)但是会发生的是程序迭代A-Z并且只在csv文件中留下Z.我希望它能在csv文件中编写A-Z中的所有内容,而不仅仅是Z中的内容。

我的代码:

     for(int t=0; t<superArray.size(); t++) {

         String temp = superArray.get(t).character;
         int temp2 = superArray.get(t).quantity;
         int temp3 = superArray.get(t).width;
         String temp4 = superArray.get(t).color;
         int temp5 = superArray.get(t).height;

         String eol = System.getProperty("line.separator");

         String line=temp+","+temp2+","+temp3+","+temp4+","+temp5 + eol;


         File myFoo = new File("Letters.csv");
         FileWriter fooWriter = new FileWriter(myFoo, true); 


         fooWriter.write(line);
         fooWriter.close();

接下来我想尝试了..我想也许我可以做(myFoo,true),在我写入文件之前,我会清除csv文件的原始内容。所以它会附加到一个空的csv文件。

         File myFoo = new File("Letter_Inventory.csv");
         myFoo.createNewFile();
         FileWriter fooWriter = new FileWriter(myFoo, true);

逻辑对我来说听起来不错,但显然没有用,所以我现在在这里。有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

每次迭代for循环都会重新打开和关闭文件!这将覆盖从循环的先前迭代中写入文件的任何内容。解决方案是:不要那样做。打开文件一次并执行之前 for循环。

更改

for(int t=0; t<superArray.size(); t++) {

     // ....etc....
     String line=temp+","+temp2+","+temp3+","+temp4+","+temp5 + eol;

     File myFoo = new File("Letters.csv");
     FileWriter fooWriter = new FileWriter(myFoo, true); 


     fooWriter.write(line);
     fooWriter.close();
}

到这个

// file created *before* the for loop
File myFoo = new File("Letters.csv");
FileWriter fooWriter = new FileWriter(myFoo, true); 

for(int t=0; t<superArray.size(); t++) {

     // .... etc ....
     String line=temp+","+temp2+","+temp3+","+temp4+","+temp5 + eol;
     fooWriter.write(line); // line written inside for loop

}

// this should be in the finally block.
fooWriter.close();