Java FileWriter false将文件从字符串A覆盖到Z,但只保留字符串Z;如何保持字符串A-Z?
因此,我的程序中有以下代码。我要做的是将我在程序主界面中声明的变量打印到一个csv文件中。我想替换csv文件中已经存在的内容(在我们访问这部分代码之前,该文件已经存在,所以我们所要做的就是替换已经存在的内容)。现在,我尝试了(myFoo,false),但实际情况是程序在A-Z中迭代,在csv文件中只留下Z。我希望它在csv文件中写入从A-Z开始的所有内容,而不仅仅是Z处的内容 我的代码:Java FileWriter false将文件从字符串A覆盖到Z,但只保留字符串Z;如何保持字符串A-Z?,java,append,filewriter,Java,Append,Filewriter,因此,我的程序中有以下代码。我要做的是将我在程序主界面中声明的变量打印到一个csv文件中。我想替换csv文件中已经存在的内容(在我们访问这部分代码之前,该文件已经存在,所以我们所要做的就是替换已经存在的内容)。现在,我尝试了(myFoo,false),但实际情况是程序在A-Z中迭代,在csv文件中只留下Z。我希望它在csv文件中写入从A-Z开始的所有内容,而不仅仅是Z处的内容 我的代码: for(int t=0; t<superArray.size(); t++) {
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();
这个逻辑听起来不错,但显然不起作用,所以我现在就在这里。有什么想法吗?谢谢 在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();
}
for(int t=0;t就是这样做的。我只需将true更改为false,这样它就可以覆盖而不是追加。谢谢!
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();