stu nicholls dot com | menu - Professional dropdown #3

Java Streams

A stream is a path traveled by data in a program. To bring in information a program opens a stream on an information source (a file, memory, a socket) and reads the information serially.

Similarly a program can send information to an external destination by opening a stream to a destination and writing the information out serially.

Depending upon the direction of the data, streams are classified into TWO categories:
1) Input Streams
2) Output Streams

Input Stream

Input Streams: Bringing Information in.To bring in information, open a stream on an information source (a file, memory, or socket) and read the information serially.

Output Stream

Output Stream:Sending Information Out. A program can send information to an external destination by opening a stream to a destination and writing the information out serially.

Stream classification

Depending upon data type on which they operate, Java streams are classified into 2 categories:

Stream Classes

Byte Stream Classes:

Byte stream classes have been designed to provide functional features for creating and manipulating streams and files for reading and writing bytes. Since the streams are unidirectional they can transmit bytes in only one direction and therefore java provides two kinds of bytes stream classes i.e. input stream classes and output stream classes.

Input Stream Classes

Input stream classes that are used to read 8 bit bytes, include a super class known as InputStream and a number of subclasses for supporting various input related functions.

Output Stream Classes

Output stream classes are derived from the base class OutputStream. This is an abstract class and has several subclasses and these subclasses can be used for performing output operations.



File Streams:
These handle writing and reading bytes to/from files.

FileInputStream:
A FileInputStream can be created with the FileInputStream (String constructor). The string argument should be the name of the file. After you create a file input stream you can read bytes from the stream by calling its read() method. This method returns an integer containing the next byte in the stream. If the method returns a -1 it signifies that end of the file stream has been reached.

Click here for example.

File Output Stream:
A file output stream can be created with FileOutputStream (String Constructor). The string argument should be the name of the file.

Note: You have to be careful when specifying the file to which to write an output stream. If it is the same as an existing file, the original contents will be lost when you start writing data to the stream.

You can create a FileOutputStream that appends data after the end of an existing file with the FileOutputStream (String, Boolean) constructor. The string specifies the file and the Boolean argument should equal to true to append data instead of overwriting any existing data.

The file output streams write (int) method is used to write bytes to the stream. After the last byte has been written to the file the streams close() method closes the stream.

Click here for example.

Character Stream classes

Reading/Writing Characters

The Reader and Writer implement the streams that can handle characters. The two subclasses used for handling characters in files are FileReader and FileWriter.

            

Data Streams

These are Filter streams used to read/write primitive data types instead of raw bytes.

To read primitives: DataInputStream.

To write primitives: DataOutputStream.

DataInputStream and DataOutputStream:

Click here for example 1.

Click here for example 2.

Using Data Streams

DataInputStream dis = new DataInputStream(fis);

char c = dis.readChar();

byte b = dis.readByte();

Similarly,

DataOutputStream dos =new DataOutputStream(fos);

dos.writeChar(c );

dos.writeByte(b);

Character Strings

Character strings are used to work with any text that is represented by ASCII value set or Unicode. Examples of files you can work with through a character stream are plain text files, html documents and java source files. The classes used to read and write these streams are subclasses of readers and writers. These should be used for all text input instead of dealing directly with file streams.

Reading Text Files

FileReader Stream
FileReader is the main class used when reading character streams from a file. This class inherits from InputStreamReader, which reads a file stream and converts the byte in integer value that represents Unicode characters. In the program given below the FileReader character stream is nested with BufferedReader stream because with character stream you can read one character at a time. But with BufferedReader you can read a line of text at a time using its ReadLine() method.

Click here for example.

Writing Text Files

FileWriter Stream
The FileWriter class is used to write character streams to a file. It is a subclass of OutputStreamWriter which has a behavior to convert Unicode character codes to bytes.

There are two FileWriter constructors. They are FileWriter (String) and FileWriter (String, Bollean). The string indicates the name of the file that the character string will be directed into which can include a folders path also. The optional Boolean argument should be equal to true if the file is to be appended to a existing text file. The example given below in WriteCharFile.java reads the contents from ReadCharFile.java and writes into the file test.txt. // You can directly use the names of the file in FileReader and FileWriter.

Note: There are two ways of initializing the file stream objects. All of the constructors require that we provide the name of the file either directly or indirectly by giving a file object that is already been assigned filename.

Click here for example.

Interactive Input

Reading the Input through the keyboard

Click here for example.

Using a Stream

Predefined standard streams

Programs

import java.io.*;
public class OutBytes
{
  public static void main (String args[])
  {
    int data[] = {65,66,67,68,69};
    try
    {
      FileOutputStream file = new FileOutputStream ("test");
      for(int i =0;i<data.length;i++)
      {
        file.write(data[i]);
      }
      file.close();
    }
    catch(IOException e)
    {
      System.out.println("Error");
    }
  }
}

import java.io.*;
public class InputBytes
{
  public static void main (String args[])
  {
    try
    {
      FileInputStream file = new FileInputStream ("test");
      boolean eof = false;
      int count = 0;
      while (!eof)
      {
        int in_put = file.read();
        System.out.print(in_put +" ");
        if(in_put==-1)
          eof = true;
        else
          count++;
      }
      file.close();
      System.out.println("\nTotal number of bytes read "+count);
    }
    catch(IOException e)
    {
      System.out.println("Error");
    }
  }
}

Our aim is to provide information to the knowledge seekers. 

comments powered by Disqus
click here
click here
click here
click here
click here
click here
Footer1