Home »
Java programming language
Java ObjectOutputStream writeChar() Method with Example
ObjectOutputStream Class writeChar() method: Here, we are going to learn about the writeChar() method of ObjectOutputStream Class with its syntax and example.
Submitted by Preeti Jain, on April 09, 2020
ObjectOutputStream Class writeChar() method
- writeChar() method is available in java.io package.
- writeChar() method is used to write 2 bytes of a character value.
- writeChar() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- writeChar() method may throw an exception at the time of writing the character.
IOException: This exception may throw when getting any input/output error while writing to the output stream.
Syntax:
public void writeChar(int value);
Parameter(s):
- int value – represents an integer that denotes a character to be written.
Return value:
The return type of the method is void, it returns nothing.
Example:
// Java program to demonstrate the example
// of void writeChar(int value) method of
// ObjectOutputStream
import java.io.*;
public class WriteCharOfOOS {
public static void main(String[] args) throws Exception {
// Instantiates ObjectOutputStream , ObjectInputStream
// FileInputStream and FileOutputStream
FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
ObjectOutputStream obj_out_stm = new ObjectOutputStream(file_out_stm);
FileInputStream file_in_stm = new FileInputStream("C:\\includehelp.txt");
ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);
// By using writeChar() method is to
// write the char to the stream
obj_out_stm.writeChar('a');
obj_out_stm.writeChar('d');
obj_out_stm.writeChar('e');
obj_out_stm.writeChar('b');
obj_out_stm.flush();
// By using readChar() method is to
// read the char
for (int i = 0; i < 4; ++i) {
char ch = obj_in_stm.readChar();
System.out.println("obj_in_stm.readChar(): " + ch);
}
// By using close() method is to
// close all the streams
System.out.println("Stream Shutdown... ");
file_in_stm.close();
file_out_stm.close();
obj_in_stm.close();
obj_out_stm.close();
}
}
Output
obj_in_stm.readChar(): a
obj_in_stm.readChar(): d
obj_in_stm.readChar(): e
obj_in_stm.readChar(): b
Stream Shutdown...