What is meant by stream? Explain byte stream and character stream classes with example

Stream

A stream is a way of sequentially accessing a file. In Streams, you can process the data one at a time as bulk operations are unavailable with them. But, streams supports a huge range of source and destinations including disk file, arrays, other devices, other programs, etc. In Java, a byte is not the same thing as a char. Therefore a byte stream is different from a character stream. So, Java defines two types of streams: Byte Streams and Character Streams.


Byte Streams

A byte stream access the file byte by byte. Java programs use byte streams to perform input and output of 8-bit bytes. It is suitable for any kind of file, but not quite appropriate for text files. For example, if the file is using a Unicode encoding and a character is represented with two bytes, the byte stream will treat these separately and you will need to do the conversion yourself. Byte-oriented streams do not use any encoding scheme while Character oriented streams use character encoding schemes (UNICODE). All byte stream classes are descended from InputStream and OutputStream.


Example

import java.io.*;

public class TestClass{

  public static void main(String[] args) {

    FileInputStream fis = null;

    FileOutputStream fos = null;

    try {

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

      fos = new FileOutputStream ("out.txt");

      int temp;

      while ((temp = fis.read()) != -1) //read byte by byte

      fos.write((byte)temp);        //write byte by byte

      if (fis != null)

      fis.close();

      if (fos != null)

      fos.close();

    }catch(Exception e){

      System.out.println(e);

    }

  }

}


When to use:

Byte streams should only be used for the most primitive I/O

When not to use:

You should not use Byte stream to read Character streams e.g. To read a text file


Character Streams

A character stream will read a file character by character. Character Stream is a higher-level concept than Byte Stream. A Character Stream is, effectively, a Byte Stream that has been wrapped with logic that allows it to output characters from a specific encoding. That means a character stream needs to be given the file's encoding in order to work properly. Character stream can support all types of character sets ASCII, Unicode, UTF-8, UTF-16 etc. All character stream classes are descended from Reader and Writer.


Example

import java.io.*;

public class TestClass{

  public static void main(String[] args) {

    FileReader reader = null;

    try {

      reader = new FileReader("in.txt");

      int fChar;

      while ((fChar = reader.read()) != -1) //read char by char

        System.out.println((char)fChar);          //write char by char

    }catch(Exception e){

      System.out.println(e);

    }

  }

}

When to use:

To read character streams either from Socket or File of characters

                                OR,
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. In java, 3 streams are created for us automatically. All these streams are attached to the console.
System.out :-the standard output stream
System.in :- the standard input stream
System.err:- standard error stream
Java application uses an output stream to write data to a destination, it may be a file, a peripheral device, or a socket. And uses an input stream to read data from a source, it may be a file, an array, peripheral device, or socket.


Byte Stream Classes 
The package java.io provides two sets of class hierarchies - one for handling reading and writing of bytes, and another for handling reading and writing of characters. The abstract classes InputStream and OutputStream are the roots of inheritance hierarchies handling the reading and writing of bytes respectively. Java byte streams are used to perform input and output of 8-b bytes. Though there are many classes related to byte streams the most frequently used classes are, FileInputStream and FileOutputStream. Following is an example that makes use o these two classes to copy an input file into an output file:
Example
import java.io.*;
public class IOStream
{
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
in.close(); out.close();
}
}

Character Stream Classes
Java FileWriter and FileReader classes are used to write and read data from text files. These are character-oriented classes, used for file handling in java. Java Byte streams are used to perform input and output of 8-bit bytes; whereas 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.
Example
import java.io.*;
public class FileReadwrite
{
public static void main(String args[]) throws IOException 
{
Filewriter writer = new Filewriter("D: /hello.txt");
writer.write("This \n is \n an\n example\n");
writer.close();
FileReader fr= new FileReader("D: /hello.txt");
char [] a new char[50];
fr.read(a); //reads the content to the array 
for(char c : a)
System.out.print(c); //prints the characters 
fr.close()
}
}
}
Output
This
is
an
example

                                              OR,

Stream 

A stream is a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of non-Unicode text.

Stream – A sequence of data.

Input Stream: reads data from the source.

Output Stream: writes data to the destination.

Character Stream

In Java, characters are stored using Unicode conventions. Character stream automatically allows us to read/write data character by character. For example, FileReader and FileWriter are character streams used to read from the source and write to the destination.In Java, characters are stored using Unicode conventions. Character stream is useful when we want to process text files. These text files can be processed character by character. The character size is typically 16 bits.

// Java Program illustrating that we can read a file in

// a human-readable format using FileReader

import java.io.*; // Accessing FileReader, FileWriter, IOException

public class GfG

{

public static void main(String[] args) throws IOException

{

FileReader sourceStream = null;

try

{

sourceStream = new FileReader("test.txt");

// Reading sourcefile and writing content to

// target file character by character.

int temp;

while ((temp = sourceStream.read()) != -1)

System.out.println((char)temp);

}

finally

{

// Closing stream as no longer in use

if (sourceStream != null)

sourceStream.close();

}

}

}

Output: Shows contents of the file test.txt 


Byte Stream

Byte streams process data byte by byte (8 bits). For example, FileInputStream is used to read from the source and FileOutputStream to write to the destination. Byte oriented reads byte by byte.  A byte stream is suitable for processing raw data like binary files.

// Java Program illustrating the Byte Stream to copy

// contents of one file to another file.

import java.io.*;

public class BStream

{

public static void main(String[] args) throws IOException

{

FileInputStream sourceStream = null;

FileOutputStream targetStream = null;


try

{

sourceStream = new FileInputStream("sorcefile.txt");

targetStream = new FileOutputStream ("targetfile.txt");

// Reading source file and writing content to target

// file byte by byte

int temp;

while ((temp = sourceStream.read()) != -1)

targetStream.write((byte)temp);

}

finally

{

if (sourceStream != null)

sourceStream.close();

if (targetStream != null)

targetStream.close();

}

}

}

              


Comments

Popular posts from this blog

Suppose that a data warehouse for Big-University consists of the following four dimensions: student, course, semester, and instructor, and two measures count and avg_grade. When at the lowest conceptual level (e.g., for a given student, course, semester, and instructor combination), the avg_grade measure stores the actual course grade of the student. At higher conceptual levels, avg_grade stores the average grade for the given combination. a) Draw a snowflake schema diagram for the data warehouse. b) Starting with the base cuboid [student, course, semester, instructor], what specific OLAP operations (e.g., roll-up from semester to year) should one perform in order to list the average grade of CS courses for each BigUniversity student. c) If each dimension has five levels (including all), such as “student < major < status < university < all”, how many cuboids will this cube contain (including the base and apex cuboids)?

Discuss classification or taxonomy of virtualization at different levels.

Short note on E-Government Architecture