s, int off, int len)


On this document we will be showing a java example on how to use the write(String s, int off, int len) method of BufferedWriter Class. The write() method is overloaded. It accepts different method parameters. Below are the overloaded write() methods:

  • write(int c)
  • write(char[] cbuf, int off, int len)
  • write(String s, int off, int len)

On this java tutorial we will be discussing the method write(String s, int off, int len). This method Writes a portion of String.

If the value of the len parameter is negative then no characters are written. This is contrary to the specification of this method in the superclass, which requires that an IndexOutOfBoundsException be thrown.

A quick background on Method Overloading

Method overloading is one of the feature of java where we can use the same method name but with different method signature.

Method Syntax

public void write(String s, int off, int len)
throws IOException

Method Argument

Data Type Parameter Description
String s String to be written
int off Offset from which to start reading characters
int len Number of characters to write

Method Returns

This method returns void.


Requires Java 1.1 and up

Java BufferedWriter write(String s, int off, int len) Example

Below is a java code demonstrates the use of write(String s, int off, int len) method of BufferedWriter class. The example presented might be simple however it shows the behaviour of the write(String s, int off, int len) method. So basically this method expects a String as the first input. The second method argument off is basically just the offset, the starting index of the string s to be written. Finally, the third argument is basically the length or count of characters from the cbuff character array to write on a file. To write all the characters of the string input, the len value should be s.length() while the offset is 0.



 * A java example source code to demonstrate
 * the use of write((Strings s, int off, int len) method of BufferedWriter class

public class BufferedWriterWriteExample {

	public static void main(String[] args) {	
		//initialize a FileWriter
		FileWriter fw;
		try {
			fw = new FileWriter("C:/javatutorialhq/test.txt");
			// initialize our BufferedWriter
			BufferedWriter bw = new BufferedWriter(fw);
			System.out.println("Starting the write operation");
			// write to a file			
			String s = "test string";		
			int off = 5;
			// close the BufferedWriter object to finish operation
		} catch (IOException e) {
			// TODO Auto-generated catch block

Sample Output

Below is the sample output when you run the above example.

java lang BufferedWriter write(String s, int off, int len) example output