Byte Streams in Java

In java programming, to perform input and output of 8-bit, Byte stream is used.

Most common byte streams classes are, FileInputStream and FileOutputStream.

FileInputStream : FileInputStream is used for reads one byte at a time .

FileOutputStream : FileOutputStream is used for writes one byte at a time

Writing Bytes

Example: Write a program, to write a bytes to a  file using Byte stream class.

import java.io.*;
public class WriteBytes {
    public static void main(String args[]) throws IOException {
        byte b[] = {
            'h',
            'e',
            'l',
            'l',
            'o',
            'a',
            'd',
            'i'
        }; //create a byte array	
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("A.txt"); //open file A for write		
            out.write(b); // write byte data to file output
        } finally {
            out.close();
        }
    }
}

Result

checking file A.txt it will show following content.

Note: If there is no file A then, file A will be create automatically

helloadi

Reading bytes from a file

Suppose we have a file “A.txt”

Hello Students I am Aditya

Example: Write a program, to read a bytes from file A using Byte stream class and print on output screen.

import java.io.*;
public class ReadBytes {
    public static void main(String args[]) throws IOException {
        FileInputStream in = null;
        try { in = new FileInputStream("A.txt");
            int c;
            while ((c = in .read()) != -1) {
                System.out.print((char) c);
            }
        } finally { in .close();
        }
    }
}
Hello Students I am Aditya

Example: Write a program, to copy the content of file A into file B using Byte stream class.

Note: if there is only file A in which data is written and no file B then, file B will be create automatically.

Suppose we have a File “A”

Hello students I am aditya.  

Output: When we run above program one new file create with Name “B” and content of file “A” will be copy into file “B”.

File “B”

Hello students I am aditya.