When should I use Java StringWriter?

What is Java StringWriter

and when should I use it?

I've read the documentation and looked here , but I don't understand when I should be using it.

+3


source to share


2 answers


This is a specialized Writer

one that writes characters to StringBuffer

, and then we use a method, for example toString()

, to get the result of a string.

When used StringWriter

, you want to write a string, but the API expects Writer

or Stream

. This is compromised, you StringWriter

only use when you need to, as StringBuffer

/ StringBuilder

for writing symbols is much more natural and simple, which should be your first choice.

Here are two typical use cases StringWriter

1.Converts the stack trace to String

so that we can easily record it 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 would be when we need to copy from InputStream

to symbols on Writer

so that we can get String

later using Apache uses IOUtils # copy :

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);//copy the stream into the StringWriter
String result = writer.toString();

      

+8


source


Used to build a string char-by-char

or string-by-string

.

It is similar to StringBuilder

but uses StringBuffer

under the hood. This is preferred when you are working with an API that requires streaming or writing. If you don't have this requirement, it is more efficient to use StringBuilder

(due to synchronization overhead StringBuffer

).

Of course, this makes sense if you understand that string concatenation (eg.

String s = "abc"+"def"; //... (especially when spread throughout a loop)` 

      

- slow operation (see here ).



small, for example

StringWriter writer = new StringWriter();
writer.write('t');
writer.write("his awesome");
String result = writer.toString();
System.out.println(result); //outputs this is awesome

      

Best example:

String[] strings = /* some array of strings*/
StringWriter writer = new StringWriter();
for(String s : strings){
    writer.write(s);
}    
String result = writer.toString();
System.out.println(result);

      

+2


source







All Articles