使用BufferedWriter写入字符串

时间:2015-02-19 05:24:55

标签: java bufferedwriter stringwriter

我正在尝试使用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的任何方式都可以解决问题。

2 个答案:

答案 0 :(得分:2)

你需要打电话给&#34; flush()&#34;将缓冲区的内容刷新到输出: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#flush()

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

答案 1 :(得分:2)

对于FileWriter try-with-resources 会在close()上调用BufferedWriter,并传播到FileWriter,刷新你写的所有东西。

同样发生在StringWriter上,但是在您尝试使用其内容时会发生这种情况,此时内容为空。在flush()上致电BufferedWriter之前,您需要toString()相应的StringWriter