Java - StringWriter write(String str) method
Description
The Java StringWriter write(String str) method writes the given string.
Declaration
Following is the declaration for java.io.StringWriter.write(String str) method.
public void write(String str)
Parameters
str − String to be written.
Return Value
This method does not return a value.
Exception
NA
Example - Usage of StringWriter write(String str) method
The following example shows the usage of StringWriter write(String str) method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
String s = "Hello";
// create a new writer
StringWriter sw = new StringWriter();
// write strings
sw.write(s);
sw.write(" World");
// print result by converting to string
System.out.println("" + sw.toString());
}
}
Output
Let us compile and run the above program, this will produce the following result −
Hello World
Example - Converting written text to String
The following example shows the usage of StringWriter write(String str) method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) throws Exception {
StringWriter writer = new StringWriter();
// Writing a full string
writer.write("Hello, ");
writer.write("Linux World!");
String result = writer.toString();
System.out.println(result); // Output: Hello, Linux World!
}
}
Output
Let us compile and run the above program, this will produce the following result−
Hello, Linux World!
Explanation
A StringWriter is created.
write(String str) is called twice −
First with "Hello, "
Then with "Linux World!"
The strings are concatenated in the buffer.
toString() returns the combined string: "Hello, Linux World!".
Example - Writing Part of a String (Substring)
The following example shows the usage of StringWriter write(String str) method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
StringWriter writer = new StringWriter();
String text = "Welcome to Java Programming!";
// Writing a substring (from index 11, length 4)
writer.write(text, 11, 4); // "Java"
String result = writer.toString();
System.out.println(result); // Output: Java
}
}
Output
Let us compile and run the above program, this will produce the following result−
Java
Explanation
The original string is "Welcome to Java Programming!".
write(text, 11, 4) writes−
From index 11 ('J' in "Java").
4 characters → "Java".
The buffer contains only "Java".