Signup/Sign In

StringWriter write() method in Java

In this tutorial, we will learn about the write() method of StringWriter class in Java. As we previously learned this class is used to write the data on the stream, these overloadings write() methods are the most important methods to write the data. This method writes the data to the stream.

Syntax

This is the syntax declaration of the write() method, this method does not return anything.

public void write(String str,int off,int len)

Example 1

In this example, we are going to demonstrate the use of the write method in the StringWriter class. Here we are taking three parameters as input and those parameters are the source of string, offset(it is a position from where it starts reading source data) and the length of the string. When we call this method based on the parameters it writes the string to the buffer.

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		String str = "Hello Studytonight";
		StringWriter stringWriter = new StringWriter();
		
		stringWriter.write(str, 0, 5);
		
		System.out.println("" + stringWriter.toString());
	} 
}


Hello

Example 2

In this example, we are using one of the overloading methods of the write() method, this method accepts the single character as a parameter and writes it to the stream.

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		StringWriter stringWriter = new StringWriter();
		
		stringWriter.write('A');
		
		System.out.println("" + stringWriter.toString());
	} 
}


A

Example 3

In this example, we are going to demonstrate the use of the write method in the StringWriter class. Here we are taking three parameters as input and those parameters are the source of the char array, offset(it is a position from where it starts reading source data) and the length of the string. When we call this method based on the parameters it writes the char array of a particular range to the buffer.

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		char arr[] = {'S', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't'};
		StringWriter stringWriter = new StringWriter();
		
		stringWriter.write(arr, 0, 5);
		
		System.out.println("" + stringWriter.toString());
	} 
}


Study

Conclusion

In this tutorial, we learned about the write() method of StringWriter class in Java. This method is used to write the data to the stream and it comes with the other overloading methods to provide flexibility over slicing and ranges of the source data.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.