tags:

views:

47

answers:

2

In Java 1.5, how can I clone an instance of java.io.CharArrayWriter?

CharArrayWriter x = new CharArrayWriter(200);
x.write("foo bar bob");

CharArrayWriter y = x.clone();   //  Object.clone() is not visible!!

Thanks,
mobiGeek

+4  A: 

There is no clone method, but you can use writeTo method.

CharArrayWriter copy = new CharArrayWriter(x.size());
x.writeTo(copy);
notnoop
Awesome! Thanks!
mobiGeek
A: 

CharArrayWriter is not cloneable. Depending on your actual requirement you can do similar with:

CharArrayWriter y = new CharArrayWriter();
y.write( x.toCharArray() );

Which is essentially the same thing.

PSpeed
writeTo() is a better solution as it avoids an extra array copy.
PSpeed
False. CharArrayWriter extends Writer which has a write(char[]) method. Check the docs... and anyone else who voted me down on that. ;)
PSpeed