3

我正在尝试使用 aBufferedWriter在写入 aFile和写入 a之间切换String,但我从未使用 aBufferedWriter写入文件以外的任何内容。

拿这个可编译的代码:

public static void main(String[] args) {
    try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(new File("file.txt")));
            StringWriter sw = new StringWriter();
            BufferedWriter stringWriter = new BufferedWriter(sw)) {

        LinkedList<Record> records = new LinkedList<>();
        records.add(new Record("name1", "text1", 20.4));
        records.add(new Record("name2", "text2", -78));
        records.add(new Record("name3", "text3", 11.56));
        records.add(new Record("name4", "text4", 56));
        records.add(new Record("name3", "text3", -44));

        for(Record record : records) {
            BufferedWriter writer;
            if(record.amount < 0) {
                writer = stringWriter; // write to string if amount is less than zero
            } else {
                writer = fileWriter; // write to file if not
            }

            writer.append(record.name);
            writer.append(",");
            writer.append(record.text);
            writer.append(",");
            writer.append(String.valueOf(record.amount));
            writer.newLine();

        }

        String less_than_zero_amounts = sw.toString();
        System.out.println("Less than zero:" + less_than_zero_amounts);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

static class Record {
    String name;
    String text;
    double amount;

    public Record(String name, String text, double amount) {
        this.name = name;
        this.text = text;
        this.amount = amount;
    }

    public String getText() {
        return text;
    }

    public String getName() {
        return name;
    }

    public double getAmount() {
        return amount;
    }
}

文件的输出是(正确)

name1,text1,20.4
name3,text3,11.56
name4,text4,56.0

但是程序的输出不打印StringWriter.

诚然,使用 aStringWriter并将其提供给 theBufferedWriter是一种预感。任何我可以将 a 切换BufferedWriter到输出的方式String都可以解决问题。

4

2 回答 2

4

您需要调用“flush()”将缓冲区的内容刷新到输出: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#flush()

虽然我应该补充一点,而不是在 BufferedWriter 对象之间进行选择,但您可能只想在Writer对象之间进行选择... StringWriter 有自己的缓冲区,因此无需在其上添加额外的 BufferedWriter 层.

于 2015-02-19T05:27:39.490 回答
3

在 的情况下FileWritertry-with-resources调用传播到close()并刷新您编写的所有内容。BufferedWriterFileWriter

也发生了同样的情况StringWriter,但它发生在你尝试使用它的内容之后,此时它是空的。您需要在调用之前进行flush()相应的操作。BufferedWritertoString()StringWriter

于 2015-02-19T05:30:30.097 回答