Byte Stream Classes

Byte stream flow information in forms of 0 and 1's. In order to perform any operation reading or writing, first we need a stream ( a connection between the program and destination/source). Theoretically every program can be written as

 
	        1. Open a Stream
2. Perform operation (Read/Write)
3. Close Stream

Now question is how to open a stream. For opening a stream we need to create an object of stream class. There are a number of byte stream classes.


InputStream and OutputStream are abstract class. These classes can't be instantiated. Their child classes shown in diagram can be used for I/O operations.

1. Open a stream

For example we want to read from a file. then one stream is needed to be created. So for that FileInputStream class object has to be created.

Syntax :


  FileInputStream fis=new FileInputStream("one.txt");
	  

File name need to specified in the constructor of FileInputStream class. Above statement will create a stream between file one.txt and our program. Once stream is created, operation can be performed on stream.

2. Perform operation

In first step byte stream is created, Now we will read data from file. Stream is byte, so all we can read is bytes. "read()" method is used to read bytes from file. This method will read one byte at a time.

Code :


FileInputStream fis=new FileInputStream("one.txt");
byte b=fis.read();
System.out.println((char)b);

Above code will read only one byte and return in the form of integer, in case if file is having multiple bytes then "read()" method need to be called multiple times.

Code :


FileInputStream fis=new FileInputStream("one.txt");
int b;
do
{
b=fis.read();
System.out.println((char)b);
} while(b!=-1);

Whenever end of file occurred in java, read method will return -1. It is used as termintating condition in loop. In above code loop will be executed until b is -1.

3. Close the stream

For closing stream "close()" method is used.

Syntax :


 fis.close();
         


Program to read from a file using Byte stream


import java.io.*;
class fileread
{
public static void main(String arg[])

{
try
{
FileInputStream fis=new FileInputStream("one.txt");
int b;
do
{
b=fis.read();
System.out.println((char)b);
}while(b!=-1);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}


Program to write to file


import java.io.*;
class filewrite
{
public static void main(String arg[])
{
try
{
FileOutputStream fis=new FileOutputStream("one.txt");
fis.write((int)'T');
fis.write((int)'h');
fis.write((int)'i');
fis.write((int)'s');
fis.write((int)' ');
fis.write((int)'i');
fis.write((int)'s');
fis.write((int)' ');
fis.write((int)'d');
fis.write((int)'e');
fis.write((int)'m');
fis.write((int)'o');
}
catch(Exception e)
{
e.printStackTrace();
}
}
}