Streams

Streams
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.
A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.
No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a time:

A program uses an output stream to write data to a destination, one item at time:

The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a network socket, or an array.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are: -
1. Byte Stream Classes: - Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are , FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file:
Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream.

These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc.
Stream classDescription
BufferedInputStreamUsed for Buffered Input Stream.
BufferedOutputStreamUsed for Buffered Output Stream.
DataInputStreamContains method for reading java standard datatype
DataOutputStreamAn output stream that contain method for writing java standard data type
FileInputStreamInput stream that reads from a file
FileOutputStreamOutput stream that write to a file.
InputStreamAbstract class that describe stream input.
OutputStreamAbstract class that describe stream output.
PrintStreamOutput Stream that contain print() and println() method

Example: -
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close(); }
}
}
}
Output: - This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:
C:\java>javac CopyFile.java
C:\java>java CopyFile
C:\java>type output.txt
This is test for copy file.
2. Character Streams: - Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are , FileReader and FileWriter.. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
We can re-write above example which makes use of these two classes to copy an input file (having unicode characters) into an output file:
Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer.
Stream classDescription
BufferedReaderHandles buffered input stream.
BufferedWriterHandles buffered output stream.
FileReaderInput stream that reads from file.
FileWriterOutput stream that writes to file.
InputStreamReaderInput stream that translate byte to character
OutputStreamReaderOutput stream that translate character to byte.
PrintWriterOutput Stream that contain print() and println() method.
ReaderAbstract class that define character stream input
WriterAbstract class that define character stream output

import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
C:\java>java CopyFile
C:\java>type output.txt
This is test for copy file.
C:\java>javac CopyFile.java
C:\java>java CopyFile
C:\java>type output.txt
This is test for copy file.
Standard Streams
Java provides following three standard streams : -
* Standard Input: - This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in.
* Standard Output: - This is used to output the data produced by the user's program and usually a computer screen is used to standard output stream and represented as System.out.
* Standard Error:- This is used to output the error data produced by the user's program and usually a computer screen is used to standard error stream and represented as System.err.
Reading and Writing Files:
A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

Input Stream Reader:
Java’s input from “System.in” console, there are two common ways to read input from console
1. InputStreamReader wrapped in a BufferedReader
2. Scanner classes in JDK1.5 or above
Output Stream Reader:
The java.io.OutputStream.write(byte[] b) method writes b.length bytes from the specified byte array to this output stream. The general contract for write(b) is that it should have exactly the same effect as the call write(b, 0, b.length)
The OutputStream class is the base class of all output streams in the Java IO API. Subclasses include the BufferedOutputStream and the FileOutputStream among others.
OutputStream's are used for writing byte based data, one byte at a time. Here is an example:
OutputStream output = new FileOutputStream("c:\\data\\output-text.txt");
while(moreData) {
int data = getMoreData();
output.write(data);
}
output.close();
Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.
The write() method of an OutputStream takes an int which contains the byte value of the byte to write.
Subclasses of OutputStream may have alternative write() methods. For instance, the DataOutputStream allows you to write Java primitives like int, long, float, double, boolean etc. with its corresponding methods writeBoolean(), writeDouble() etc.
InputStreamReader wrapped in a BufferedReader
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and translates them into characters according to a specified character encoding. The encoding that it uses may be specified by name, or the platform's default encoding may be accepted.
Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.
For top efficiency, consider wrapping an InputStreamReader within a BufferedReader.
Class constructors
S.no Constructor & Description
1 InputStreamReader(InputStream in)
This creates an InputStreamReader that uses the default charset.
2 InputStreamReader(InputStream in, Charset cs)
This creates an InputStreamReader that uses the given charset.
3 InputStreamReader(InputStream in, CharsetDecoder dec)
This creates an InputStreamReader that uses the given charset decoder.
4 InputStreamReader(InputStream in, String charsetName)
This creates an InputStreamReader that uses the named charset.
Class methods
S.no Method & Description
1 void close()
This method closes the stream and releases any system resources associated with it.
2 String getEncoding()
This method returns the name of the character encoding being used by this stream.
3 int read()
This method reads a single character.
4 int read(char[] cbuf, int offset, int length)
This method reads characters into a portion of an array.
5 boolean ready()
This method tells whether this stream is ready to be read.

BufferedReader
The BufferedReader class provides buffering to your Reader's. Buffering can speed up IO quite a bit. Rather than read one character at a time from the network or disk, you read a larger block at a time. This is typically much faster, especially for disk access and larger data amounts. The main difference between BufferedReader and BufferedInputStream is that Reader's work on characters (text), wheres InputStream's works on raw bytes. To add buffering to your Reader's simply wrap them in a BufferedReader. Here is how that looks: Reader input = new BufferedReader( new FileReader("c:\\data\\input-file.txt"));
* The buffer size may be specified, or the default size may be used.
* Each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.
1 BufferedReader(Reader in): - This creates a buffering character-input stream that uses a default-sized input buffer.
2 BufferedReader(Reader in, int sz): - This creates a buffering character-input stream that uses an input buffer of the specified size.
S.no. Method & Description
1 void close()
This method closes the stream and releases any system resources associated with it.
2 void mark(int readAheadLimit)
This method marks the present position in the stream.
3 boolean markSupported()
This method tells whether this stream supports the mark() operation, which it does.
4 int read()
This method reads a single character.
5 int read(char[] cbuf, int off, int len)
This method reads characters into a portion of an array.
6 String readLine()
This method reads a line of text.
7 boolean ready()
This method tells whether this stream is ready to be read.
8 void reset()
This method resets the stream.
9 long skip(long n)
This method skips characters.

Example: -
import java.io.*;
class sample4 {
public static void main(String[] args)throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
double product1 = 2.98,product2=4.50,product3=9.98,product4=4.49,product5=6.87;
int hold,value;
double total;
System.out.print("Choices of Product! \n[1]Product1 \n[2]Product2 \n[3]Product3 \n[4]Product4 \n[5]Product5 \nChoose Product : ");
hold=Integer.parseInt(in.readLine());
switch(hold){
case 1:
System.out.println("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product1*value;
System.out.println("Product number 1:");
System.out.println("Quantity sold: "+value);
System.out.print("Amount to be paid: "+total+"$");
break;
case 2:
System.out.println("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product2*value;
System.out.println("Product number 2:");
System.out.println("Quantity sold: "+value);
System.out.print("Amount to be paid: "+total+"$");
break;
case 3:
System.out.println("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product3*value;
System.out.println("Product number 3:");
System.out.println("Quantity sold: "+value);
System.out.print("Amount to be paid: "+total+"$");
break;
case 4:
System.out.println("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product4*value;
System.out.println("Product number 4:");
System.out.println("Quantity sold: "+value);
System.out.print("Amount to be paid: "+total+"$");
break;
case 5:
System.out.println("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product5*value;
System.out.println("Product number 5:");
System.out.println("Quantity sold: "+value); System.out.print("Amount to be paid: "+total+"$");
break; }
}
}
Output: - C:\java>javac sample4.java
C:\java>java sample4
Choices of Product!
[1]Product1
[2]Product2
[3]Product3
[4]Product4
[5]Product5
Choose Product : 2
Quantity you want?:
20
Product number 2:
Quantity sold: 20
Amount to be paid: 90.0$


Free Web Hosting