Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BufferedWriter to write to a string [duplicate]

I am trying to use a BufferedWriter to switch between writing to a File and writing to a String, but I have never used a BufferedWriter to write to anything but a file.

Take this compilable code:

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;
    }
}

The output for the file is (correctly)

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

But the output for the program does not print the StringWriter.

Admittedly, using a StringWriter and giving that to the BufferedWriter was a hunch. Any way I can switch a BufferedWriter to output to a String would solve the problem.

like image 822
ryvantage Avatar asked Oct 29 '25 12:10

ryvantage


2 Answers

You need to call "flush()" to flush the contents of the buffer to the output: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#flush()

Though I should add that rather than select between BufferedWriter objects, you probably want to simply select between Writer objects... the StringWriter has a buffer of its own, so there is no need to add an extra layer of a BufferedWriter on top of it.

like image 53
Michael Aaron Safyan Avatar answered Oct 31 '25 02:10

Michael Aaron Safyan


In the case of the FileWriter, the try-with-resources calls close() on the BufferedWriter which propagates to the FileWriter and flushes everything you've written.

The same happens to the StringWriter, but it happens after you've tried to consume its contents, which at that point are empty. You need to flush() the corresponding BufferedWriter before you call toString() on the StringWriter.

like image 34
Sotirios Delimanolis Avatar answered Oct 31 '25 01:10

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!