我为缓冲编写器设置了一个循环,将一个字符串数组写入一个文件,看起来很简单吧?好吧,出于某种原因,我确信我会因为错过它而感到愚蠢,但它会在每次迭代时写入前一行文本。
以下是循环
for(int i = 0; listnames.length > i; i++){
String[] data = getItemsandAisles(listnames[i]);
for(int x = 0; data.length > x; x ++){
BufferedWriter bw = new BufferedWriter(new FileWriter(listfile[i]));
System.out.println("Writing " + data[x] + " to file " + listfile[i].getAbsolutePath());
bw.write(data[x]);
bw.flush();
bw.newLine();
bw.close();
}
}
这是我输入的所有输出的日志cat,这只是第一次迭代,因为它拥有最多的项目
Writing COFFEE CREAMERS 5 to file /data/data/dev.shaw.MyShoppingPlanner/files/sample list.txt
Writing SAUCES APPLE CRANBERRY 6 to file /data/data/dev.shaw.MyShoppingPlanner/files/sample list.txt
Writing COCOA 5 to file /data/data/dev.shaw.MyShoppingPlanner/files/sample list.txt
Writing UMBRELLAS Front End Rack to file /data/data/dev.shaw.MyShoppingPlanner/files/sample list.txt
Writing PET NEEDS 9A\/B to file /data/data/dev.shaw.MyShoppingPlanner/files/sample list.txt
Writing ITALIAN CHEESE 17 to file /data/data/dev.shaw.MyShoppingPlanner/files/sample list.txt
Writing EGGS Dairy to file /data/data/dev.shaw.MyShoppingPlanner/files/sample list.txt
Writing BACON Meat to file /data/data/dev.shaw.MyShoppingPlanner/files/sample list.txt
然后从设备下载txt文件时的最终输出只是一行
BACON Meat
这使我相信它实际上并没有创造新的一条线。任何帮助将不胜感激。我知道这里有一些类似的问题,但我尝试了所有这些解决方案,但他们似乎并没有解决这个问题。
答案 0 :(得分:0)
尝试在第二个循环之前打开文件,如下所示:
for(int i = 0; listnames.length > i; i++){
BufferedWriter bw = new BufferedWriter(new FileWriter(listfile[i]));
String[] data = getItemsandAisles(listnames[i]);
for(int x = 0; data.length > x; x ++){
System.out.println("Writing " + data[x] + " to file " + listfile[i].getAbsolutePath());
bw.write(data[x]);
bw.newLine();
//bw.flush(); --> not necessary here unless you really need the data on the disk "right now"
}
bw.flush();
bw.close();
}
或者更好,也许您想要使用StringBuilder
,如下所示。
for(int i = 0; listnames.length > i; i++){
StringBuilder sb = new StringBuilder();
String[] data = getItemsandAisles(listnames[i]);
for(int x = 0; data.length > x; x ++){
System.out.println("Writing " + data[x] + " to file " + listfile[i].getAbsolutePath());
sb.append(data[x]).append("\n");
}
BufferedWriter bw = new BufferedWriter(new FileWriter(listfile[i]));
bw.write(sb.toString());
bw.flush();
bw.close();
}
然而,BufferedWriter
本身的目的是将多次写入缓冲到一次大写中。所以,你的选择。 =)