Character Stream & Byte Stream

Character Stream

In Java, characters are stored using Unicode conventions. Character stream automatically allows us to read/write data character by character. For example, FileReader and FileWriter are character streams used to read from the source and write to the destination.

Character stream uses buffers by default. So nothing will be outputed before the stream has been closed with close or flush method.

code example for Character Stream:

import java.io.*;
 
public class GFG {
 
	public static void main(String[] args) throws IOException {
		FileReader sourceStream = null;
		
		try {
			sourceStream = new FileReader(
				"/Users/mayanksolanki/Desktop/demo.rtf");
			int temp;
			while ((temp = sourceStream.read()) != -1) {
				System.out.println((char)temp);
			}
    		System.out.print("Program successfully executed");
		} finally {
			if (sourceStream != null)
				sourceStream.close();
		}
	}
}

Byte Stream

Byte streams process data byte by byte (8 bits). For example, FileInputStream is used to read from the source and FileOutputStream to write to the destination.

Byte streams don’t use buffers by default.

code example for Byte Stream:

import java.io.*;
 
public class GFG {
	public static void main(String[] args) throws IOException {
		FileInputStream sourceStream = null;
		FileOutputStream targetStream = null;
		
		try {
			sourceStream = new FileInputStream(
				"/Users/mayanksolanki/Desktop/demo.rtf");
			targetStream = new FileOutputStream(
				"/Users/mayanksolanki/Desktop/democopy.rtf");
			int temp;
			while ((temp = sourceStream.read()) != -1) {
				targetStream.write((byte)temp);
			}
    		System.out.print("Program successfully executed");
		} finally {
			if (sourceStream != null) {
				sourceStream.close();
			}
			if (targetStream != null) {
				targetStream.close();
			}
		}
	}
}