bufferedWriter写的比它更多

时间:2015-07-14 20:38:29

标签: java bufferedwriter

我正在尝试读取一些数据并将其写入数据库,我的代码如下:

try {
    // Assume default encoding.
    FileWriter fileWriter = new FileWriter(fileName);

    // Always wrap FileWriter in BufferedWriter.
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

    // Note that write() does not automatically
    // append a newline character.
    bufferedWriter.write("@relation dummy");
    bufferedWriter.newLine();
    bufferedWriter.write("@attribute unexpectedness {0, 1}");
    bufferedWriter.newLine();
    bufferedWriter.write("@data");
    bufferedWriter.newLine();
    for (String[] row : instances) {
        if (counter > 450) {
            bufferedWriter.write(row[0]+", "+row[1]+", "+row[2]+", "+row[3]+", "+row[4]+", "+row[5]+", "+row[6]+", "+row[7]+", "+row[8]);
            //  System.out.println(row[0]+", "+row[1]+", "+row[2]+", "+row[3]+", "+row[4]+", ttt "+row[5]+", "+row[6]+", "+row[7]);
            bufferedWriter.newLine();
            testRows.add(row);
        }
        else {
            counter = counter + 1;
        }
    }
    bufferedWriter.flush();
    bufferedWriter.close();
}
catch (IOException ex) {
    System.out.println("Error writing to file '" + fileName + "'");
}
finally {
    System.gc();
}

哪个有效,但问题出在我有400个元素的情况下,但令人惊讶的是缓冲写入器写了大约5000行。有人能解释为什么会这样吗?

更新

我检查了输出,似乎缓冲区写入器将每行写入文本文件8次。

1 个答案:

答案 0 :(得分:0)

您可以使用PrintWriter(让我们称之为pw)来编写这样的文件:

pw.println("bla bla");

通过这种方式,作者每次都会在新的一行上写下来。