When should I use Java’s stringwriter?
What is a Java stringwriter and when should it be used?
I've read the documentation and looked at here, but I don't know when to use it
Solution
It is a special writer, which writes characters to StringBuffer, and then we use a method similar to toString () to obtain string results
When using stringwriter, you want to write a string, but the API requires writer or stream It is a compromise. You can only use stringwriter when necessary, because StringBuffer / StringBuilder is more natural and easy to write characters, which should be your first choice
The following are two typical cases of using stringwriter
1. Convert stack trace to string so that we can record easily
StringWriter sw = new StringWriter();//create a StringWriter PrintWriter pw = new PrintWriter(sw);//create a PrintWriter using this string writer instance t.printStackTrace(pw);//print the stack trace to the print writer(it wraps the string writer sw) String s=sw.toString(); // we can Now have the stack trace as a string
2. Another case is when we need to copy characters from InputStream to writer, so that we can use Apache Commons ioutils#copy to obtain string in the future:
StringWriter writer = new StringWriter(); IoUtils.copy(inputStream,writer,encoding);//copy the stream into the StringWriter String result = writer.toString();