使用 BufferedWriter 写入字符串

Using BufferedWriter to write to a string

我正在尝试使用 BufferedWriter 在写入 File 和写入 String 之间切换,但我从未使用 BufferedWriter 写入除了文件之外的任何东西。

拿这个可编译的代码:

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

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

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

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

FileWriter 的情况下,try-with-resources 调用 BufferedWriter 上的 close() 传播到 FileWriter 并刷新你写的所有内容。

StringWriter 也会发生同样的情况,但它发生在您尝试使用其内容之后,此时内容是空的。在 StringWriter.

上调用 toString() 之前,您需要 flush() 相应的 BufferedWriter