Description

On this document we will be showing a java example on how to use the write() 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(int c). This method writes a single character. The character is defined by the int value input. You can refer to https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html for the list of ascii equivalent of each character that can be written.

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(int c) throws IOException

Method Returns

This method returns void.

Compatibility

Requires Java 1.1 and up

Java BufferedWriter write(int c) Example

Below is a java code demonstrates the use of write(int c) method of BufferedWriter class. The example presented might be simple however it shows the behaviour of the write(int c) method. Don’t get confused on the characters being written on the file because it is not straight forward. The int value as method argument is ascii equivalent of each character. Please refer to https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html for the full list of values.

package com.javatutorialhq.java.examples;


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/*
 * A java example source code to demonstrate
 * the use of write(int c) method of BufferedWriter class
 */

public class BufferedWriterWriteIntExample {

	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 values
			bw.write(65);
			bw.newLine();
			bw.write(35);
			
			// close the BufferedWriter object to finish operation
			bw.close();
			System.out.println("Finished");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
	}
}

Sample Output

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

java lang BufferedWriter write(int c) example output