在将数组写入文件

时间:2017-05-07 15:03:04

标签: java file

将数据逐行循环写入文件将导致最后一行为“换行符”。考虑一下:

try {
  outFile = new BufferedWriter(new FileWriter(outFileName));
  for (int i = 0; i < some_condition; i++) {
    for (String record: aLine) {
       outFile.write(record + " ");
    }
    outFile.write("\n");
  }
} catch(IOException e) {
  System.out.println("found error!");
}

每行中的最后一项也是“”。修剪这些空白区域和换行符的有效方法是什么?

我可以将循环分为0 ... n-2和n-1,但对于大代码不是很好。我正在寻找一些基于文件的解决方案:

try {
  outFile = new BufferedWriter(new FileWriter(outFileName));
  for (int i = 0; i < some_condition; i++) {
    for (String record: aLine) {
       outFile.write(record + " ");
    }
    outFile.REMOVE_LAST_CHARACTER;  // trim " "
    outFile.write("\n");
  }
} catch(IOException e) {
  System.out.println("found error!");
}
outFile.REMOVE_LAST_LINE;

这可能吗?

1 个答案:

答案 0 :(得分:1)

将其附加到StringBuilder,然后通过修剪character最后删除最后String,或者您可以在追加for时手动检入" "循环。对于\n换行符,您可以将每一行附加到主StringBuilder,以跟踪整个file并最后修剪extra space

StringBuilder all_lines = new StringBuilder(); //To store every line

for (int i = 0; i < some_condition; i++) {
    StringBuilder line = new StringBuilder();
    for (String record: aLine) {
        line.append(record).append(" ");       //To store every words
    }
    all_lines.append(line.toString().trim());
    all_lines.append("\n");
}

outFile.write(all_lines.toString().trim());
outFile.close();