java 使用 BufferedWriter 写入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28599154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:52:41  来源:igfitidea点击:

Using BufferedWriter to write to a string

javabufferedwriterstringwriter

提问by ryvantage

I am trying to use a BufferedWriterto switch between writing to a Fileand writing to a String, but I have never used a BufferedWriterto write to anything but a file.

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

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.

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

Admittedly, using a StringWriterand giving that to the BufferedWriterwas a hunch. Any way I can switch a BufferedWriterto output to a Stringwould solve the problem.

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

回答by Michael Aaron Safyan

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()

您需要调用“flush()”将缓冲区的内容刷新到输出: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 Writerobjects... 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.

尽管我应该添加它而不是在 BufferedWriter 对象之间进行选择,但您可能只想在Writer对象之间进行选择... StringWriter 有自己的缓冲区,因此无需在其顶部添加额外的 BufferedWriter 层.

回答by Sotirios Delimanolis

In the case of the FileWriter, the try-with-resourcescalls close()on the BufferedWriterwhich propagates to the FileWriterand flushes everything you've written.

在的情况下FileWriter,将尝试与-资源调用close()BufferedWriter其传播到FileWriter并刷新你写的一切。

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 BufferedWriterbefore you call toString()on the StringWriter.

StringWriter也会发生同样的情况,但它会在您尝试使用其内容之后发生,此时这些内容是空的。您需要flush()相应的BufferedWriter调用之前toString()StringWriter