你如何在 Java 中“清空”一个 StringWriter?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3738095/
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-10-30 03:13:39  来源:igfitidea点击:

How do you "empty" a StringWriter in Java?

javaio

提问by Derek Mahar

What is the correct way to "empty" a StringWriterin Java so that I can reuse the StringWriterwithout having to create a new one? Neither StringWriter.flush()nor StringWriter.close()seem to have the desired effect.

StringWriter在 Java 中“清空” a以便我可以重用它StringWriter而不必创建新的正确方法是什么?无论是StringWriter.flush()StringWriter.close()似乎收到预期的效果。

回答by Jon Skeet

How about calling getBuffer().setLength(0)?

打电话getBuffer().setLength(0)怎么样?

回答by Exception_al

Alternatively, we could also delete the buffer using the following code:

或者,我们也可以使用以下代码删除缓冲区:

StringBuffer buf = ****.getBuffer();
buf.delete(0,buf.length());