Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. Java I/O stream is the flow of data that you can either read from, or you can write to. It is used to perform read and write operations in file permanently. Java uses streams to perform these tasks. Java I/O stream is also called File Handling, or File I/O. It is available in java.io package and provides classes for system input and output through files, network streams, memory buffers, etc.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.
Some input-output stream will be initialized automatically by the JVM and these streams are available in System class as in, out, and err variable.
in reference refers to the default input device, i.e. keyboard.
out and err refers to the default output device, i.e. console.
Streams based on data are of two types namely:
1.Binary streams or Byte streams: These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc.
All byte stream classes are derived from base abstract classes called InputStream and OutputStream.
2.Character Streams: These handle data in 16 bit Unicode. Using these you can read and write text data only. Character stream is used to read and write a single character of data.
All the character stream classes are derived from base abstract classes Reader and Writer.
The InputStream class of the java.io package is an abstract superclass that represents an input stream of bytes. Since InputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to read data.
Diagram to illustrates all the input and output Streams (classes) in Java
Streams are the sequence of bits(data):
There are two types of streams:
1.Input Streams (File.txt which is placed in harddisk to API interface(Program shell)
2.Output Streams (API interface(Program shell) to File.txt which is placed in harddisk )
Input Streams:(FILE TO API)
Java application uses an input stream to read data from various input devices like keyboard, file, an array, peripheral device, network or socket etc.
The InputStream class of the java.io package is an abstract superclass that represents an input stream of bytes. Since InputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to read data.
Subclasses of InputStream
In order to use the functionality of InputStream, we can use its subclasses. Some of them are:
- FileInputStream
- ByteArrayInputStream
- ObjectInputStream
- BufferedInputStream
- DataInputStream
Creating an InputStream
In order to create an InputStream, we must import the java.io.InputStream package first. Once we import the package, here is how we can create the input stream.
InputStream object1 = new FileInputStream();
Here, we have created an input stream using FileInputStream. It is because InputStream is an abstract class. Hence we cannot create an object of InputStream.
The InputStream class provides different methods that are implemented by its subclasses. Here are some of the commonly used methods:
read() - reads one byte of data from the input stream
read(byte[] array) - reads bytes from the stream and stores in the specified array
available() - returns the number of bytes available in the input stream
close() - closes the input stream
Ex:
//import java.io.FileInputStream;
//import java.io.InputStream;
import java.io.*;
public class MainRead
{
public static void main(String args[])
{
byte[] array = new byte[10];
try
{
InputStream ip = new FileInputStream("input.txt");
System.out.println("Available bytes in the file: " + ip.available());
// Read byte from the input stream
ip.read(array);
System.out.println("Data read from the file: d:\\input.txt");
// Convert byte array into string
String data = new String(array);
System.out.println(data);
// Close the input stream
ip.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
//import java.io.InputStream;
import java.io.*;
public class MainRead
{
public static void main(String args[])
{
byte[] array = new byte[10];
try
{
InputStream ip = new FileInputStream("input.txt");
System.out.println("Available bytes in the file: " + ip.available());
// Read byte from the input stream
ip.read(array);
System.out.println("Data read from the file: d:\\input.txt");
// Convert byte array into string
String data = new String(array);
System.out.println(data);
// Close the input stream
ip.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
Output:
In
the above example, we have created an input stream using the
FileInputStream class. The input stream is linked with the file
input.txt.
InputStream input = new FileInputStream("input.txt");
Note:
To read data from the input.txt file, we have implemented the following two methods.
in.read(array); // to read data from the input stream
in.close(); // to close the input streamOutput Streams: (API TO FILE )
Java
application uses an output stream to write the data to various output
devices like monitor, file, an array, network, peripheral device or
socket etc.
The
OutputStream class of the java.io package is an abstract superclass
that represents an output stream of bytes. Since OutputStream is an
abstract class, it is not useful by itself. However, its subclasses can
be used to write data.
In order to use the functionality of OutputStream, we can use its subclasses.
Some of them are:
- FileOutputStream
- ByteArrayOutputStream
- ObjectOutputStream
- BufferedOutputStream
- DataOutputStream
Create an Output Stream
In order to create an OutputStream, we must import the java.io.OutputStream package first.
Creating an Output Stream
OutputStream obj=new FileOutputStream();
Methods of OutputStream ( write from API into file )
write() - writes the specified byte to the output stream
OutputStream obj=new FileOutputStream();
Here,
we have created an object of output stream using FileOutputStream. It
is because OutputStream is an abstract class, so we cannot create an
object of OutputStream.
write() - writes the specified byte to the output stream
write(byte[] array) - writes the bytes from the specified array to the output stream
flush() - forces to write all data present in output stream to the destination
close() - closes the output stream
OutputStream Using FileOutputStream
Ex:
import java.io.FileOutputStream; import java.io.OutputStream;
public class MainW
{
public static void main(String args[])
{
String data = "ram is a boy This is a line of text inside the file.";
try
{
OutputStream out = new FileOutputStream("output.txt");
// Converts the string into bytes
byte[] dataBytes = data.getBytes();
// Writes data to the output stream
out.write(dataBytes);
System.out.println("Data is written to the file.");
// Closes the output stream
out.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
Output:
Note:
To write data to the output.txt file,we have implemented these methods
output.write(); // To write data to the file
output.close(); // To close the output stream
output.close(); // To close the output stream
Character Stream classes
Character
Stream Classes are used to read characters from the source and write
characters to destination. There are two kinds of Character Stream
classes - Reader classes and Writer classes.
Reader Classes:
These classes are subclasses of an abstract class, Reader and they are
used to read characters from a source(file, memory or console).
Writer Classes:
These classes are subclasses of an abstract class, Writer and they used
to write characters to a destination(file, memory or console).
Reader class and its subclasses are used to read characters from source.
Reader
class is a base class of all the classes that are used to read
characters from a file, memory or console. Reader is an abstract class
and hence we can't instantiate it but we can use its subclasses for
reading characters from the input stream.
Methods of Reader class.
Methods Description
int read() This method reads a characters from the input stream.
int read(char[] ch) This method reads a chunk of characters from the input stream and store them in its char array, ch.
close() This method closes this output stream and also frees any system resources connected with it.
Writer:
Writer
class and its subclasses are used to write characters to a file, memory
or console. Write class is a base class of all the classes that are
used to write characters to a file, memory or console.Writer is an
abstract class and hence we can't create its object but we can use its
subclasses for writing characters to the output stream.
Methods of Writer class:
Methods
of Writer class provide support for writing characters to the output
stream. As this is an abstract class. Hence, some undefined abstract
methods are defined in ths subclasses of OutputStream.
Methods Description
abstract void flush() This method flushes the output steam by forcing out buffered bytes to be written out.
abstract void flush() This method flushes the output steam by forcing out buffered bytes to be written out.
void write(int c) This method writes a characters(contained in an int) to the output stream.
void write(char[] arr) This method writes a whole char array(arr) to the output stream.
abstract void close() This method closes this output stream and also frees any resources connected with this output stream.
Example :Program to create a file, write data to the file, read and display the contents of the file. (OR)
Write a program to demonstrate Input / Output Streams in Java.
Note : You need to write two programs(need to create two files), One to input the data and the other to read the data.
Write a program to demonstrate Input / Output Streams in Java.
Note : You need to write two programs(need to create two files), One to input the data and the other to read the data.
File Name : FileCreation.java ( API TO FILE )
Note: The above file is used to input the data which in turn save the inputted data into a file named “rkdata.txt” )
import java.io.*;
public class FileCreation
{
public static void main(String[] args)
{
try
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader b=new BufferedReader(is);
String st=null,ct="";
char res='t';
Writer w = new FileWriter("rkdata.txt");
//String content = "This is to add a single line text...";
while(res!='x')
{
st=b.readLine(); //Reads data in the stream character wise.
res=st.charAt(0);
if(res=='x')
break;
ct=ct+st+"\r\n"; //here \r\n combination is to produce a new line
}
w.write(ct);
w.close();
System.out.println("File Is Saved!!!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Note: The above file is used to input the data which in turn save the inputted data into a file named “rkdata.txt” )
import java.io.*;
public class FileCreation
{
public static void main(String[] args)
{
try
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader b=new BufferedReader(is);
String st=null,ct="";
char res='t';
Writer w = new FileWriter("rkdata.txt");
//String content = "This is to add a single line text...";
while(res!='x')
{
st=b.readLine(); //Reads data in the stream character wise.
res=st.charAt(0);
if(res=='x')
break;
ct=ct+st+"\r\n"; //here \r\n combination is to produce a new line
}
w.write(ct);
w.close();
System.out.println("File Is Saved!!!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Output:
Command to compile: I:\>javac FileCreation.java
Command to execute I:\>java FileCreation
ram is a boy
ram is a boy
x
File Is Saved!!!
Now check out your file rkdata.txt file
File Is Saved!!!
Now check out your file rkdata.txt file
File Name : FileRead.java (file to API )
Note: The above file is used to read the data from the file named “vldata.txt” )
import java.io.*;Note: The above file is used to read the data from the file named “vldata.txt” )
public class FileRead
{
public static void main(String[] args)
{
BufferedReader br=null;
try
{
String s;
br=new BufferedReader(new FileReader("vldata.txt"));
while ((s=br.readLine()) != null)
{
System.out.println(s);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br!=null)
br.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
}
Output: