StringWriter(int): This method is available in the java.io.StringWriter class of Java.
Syntax:
java.io.StringWriter.StringWriter(int initialSize)
This method takes one argument. This method creates a new string writer using the specified initial string buffer size.
Parameters: One parameter is required for this method.
initialSize: The number of char values that will fit into this buffer before it is automatically expanded.
Throws:
1. IllegalArgumentException - If initialSize is negative
Approach 1: When no exception
Java
import java.io.IOException;import java.io.StringWriter;public class StringWriterStringWriter2 {public static void main(String[] args) throws IOException {int initialSize = 100;StringWriter stringWriter =new StringWriter(initialSize);stringWriter.append("HELLO");System.out.println(stringWriter);}}
Output:
HELLO
Approach 2: IllegalArgumentException
Java
package com.StringWriter;import java.io.IOException;import java.io.StringWriter;public class StringWriterStringWriter2 {public static void main(String[] args) throws IOException {int initialSize = -100;StringWriter stringWriter =new StringWriter(initialSize);stringWriter.append("HELLO");System.out.println(stringWriter);}}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Negative buffer size at java.base/java.io.StringWriter.<init>(StringWriter.java:67) at com.StringWriter.StringWriterStringWriter2.main(StringWriterStringWriter2.java:10)
Some other methods of StringWriter
append(char): This method appends the specified character to this writer.
append(CharSequence): This method appends the specified character sequence to this writer.
append(CharSequence, int, int): This method appends a subsequence of the specified character sequence to this writer.
close(): This method closes a StringWriter.
flush(): This method flushes the stream.
getBuffer(): This method returns the string buffer itself.
StringWriter(): This method creates a new string writer using the default initial string buffer size.
StringWriter(int): This method creates a new string writer using the specified initial string buffer size.
toString(): This method returns the buffer's current value as a string.
write(int): This method writes a single character.
write(String): This method writes a string.
write(char[], int, int): This method writes a portion of an array of characters.
write(String, int, int): This method writes a portion of a string.
No comments:
Post a Comment