Streams(IO Streams) in Java

Posted on

        Streams can be categorized into the following:

  1. Byte streams.
  2. Character streams.

Byte Streams

         Byte Streams allow you to read and write information purely in the form of bytes. Byte Streams are ruled by two top most abstract classes namely

InputStream class.OutputStream class.
InputStream Class:
         An abstract class all of whose methods would raise an IOException, which must be caught either by using the try … catch ( or ) by using the throws clause.

Methods:

int available(); Returns the number of bytes available for input.

int read(); Returns the integer representation of the next available byte for input. At the end of file returns -1.

int read(byte buffer[ ]); Attempts to read upto buffer.length characters from the invoking stream and stores them into the byte array “buffer”. It also returns the number of bytes returned.

int read(byte buffer[ ], int offset, int numBytes); Attempts to read “numBytes” bytes from the invoking stream and stores them in the byte array “buffer” starting at “offset”.

void close(); Closes the stream object.
Outputstream class:
         An abstract classes all of whose methods would raise an IOException, which must be caught.

void close(); closes the stream object.

Void write(int n); Writes the integer representation.

Void write(byte buffer[]); Attempts to write upto buffer.length bytes into the invoking stream.

Void write(byte buffer[], int offset, int bytes); Attempts to write “numBytes” bytes from the byte array “buffer” starting at “offset” into the invoking stream.
FileInputStream class

         The “file input stream class returns as an “input stream” for the specified file.

Constructors:
File InputStream(String filename);File InputStream(File fileobject);
Throws clause:

         To handle run-time exceptions the first way is to use “try…catch block”. The alternate is the usage of the “throws clause”. The throws clause is mostly used with method. The use of the try…catch block makes your code lengthier. Instead of that you can use the throw clause. The throws clause is mostly preferred for the built-in methods which by default raise run-time exception. One demerit of the throws clause is that you cannot customize the error message.

Usage:

return_type method([args]) throws exception_list
{
……………………….
body of the method.
………………………
}

import java.io.*;
class App71
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
int n;
n=inp.read();
while(n!=-1)
{
System.out.print((char)n);
n=inp.read();
}
inp.close();
}
}


output:

\>javac App71.java
\>java App71 App71.java
import java.io.*;
class App71
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
int n;
n=inp.read();
while(n!=-1)
{
System.out.print((char)n);
n=inp.read();
}
inp.close();
}
}
import java.io.*;
class App72
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
int n;
char ch;
n=inp.read();
while(n!=-1)
{
ch=(char)n;
System.out.print(Character.toUpperCase(ch));
n=inp.read();
}
inp.close();
}
}


output:

\>javac App72.java
\>java App72 App72.java
IMPORT JAVA.IO.*;
CLASS APP72
{
PUBLIC STATIC VOID MAIN(STRING YCK[]) THROWS IOEXCEPTION
{
INPUTSTREAM INP=NEW FILEINPUTSTREAM(YCK[0]);
INT N;
CHAR CH;
N=INP.READ();
WHILE(N!=-1)
{
CH=(CHAR)N;
SYSTEM.OUT.PRINT(CHARACTER.TOUPPERCASE(CH));
N=INP.READ();
}
INP.CLOSE();
}
}
import java.io.*;
class App73
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
int n,upper,lower,digits,spaces,vowels;
char ch;
upper=digits=lower=spaces=vowels=0;
n=inp.read();
while(n!=-1)
{
ch=(char)n;
if (Character.isUpperCase(ch))
upper++;
else
if (Character.isLowerCase(ch))
lower++;
else
if (Character.isDigit(ch))
digits++;
else
if (Character.isWhitespace(ch))
spaces++;
switch(Character.toUpperCase(ch))
{
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : vowels++;
}
n=inp.read();
}
inp.close();
System.out.println("Upper case :"+upper);
System.out.println("Lower case :"+lower);
System.out.println("Digits :"+digits);
System.out.println("Spaces :"+spaces);
System.out.println("Vowels :"+vowels);
}
}


output:

\>javac App73.java
\>java App73 App73.java
Upper case :41
Lower case :521
Digits :5
Spaces :242
Vowels :198
import java.io.*;
class App74
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
byte x[]=new byte[inp.available()];
inp.read(x);
inp.close();
System.out.println("Contents of the buffer ...");
for(int i=0;i System.out.print((char)x[i]);
}
}


output:

\>javac App74.java
\>java App74 App73.java
import java.io.*;
class App74
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
byte x[]=new byte[inp.available()];
inp.read(x);
inp.close();
System.out.println("Contents of the buffer ...");
for(int i=0;i System.out.print((char)x[i]);
}
}
import java.io.*;
class App75
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
byte x[]=new byte[inp.available()];
inp.read(x,0,150);
inp.close();
System.out.println("Contents of the buffer ...");
for(int i=0;i System.out.print((char)x[i]);
}
}


output:

\>javac App75.java
\>java App75 App75.java
import java.io.*;
class App75
{
public static void main(String yck[]) throws IOException
{
InputStr

FileOutputStream:
         Creates an ‘outputStream’ for the invoking file.

Constructor:

  1. FileOutputStream(Stream filename);
  2. FileOutputStream(File object);
import java.io.*;
class App76
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
OutputStream out=new FileOutputStream(yck[1]);
int n;
n=inp.read();
while(n!=-1)
{
out.write(n);
n=inp.read();
}
inp.close();
out.close();
}
}


output:

\>javac App76.java
\>java App76 App76.java sample.txt
\>type sample.txt
import java.io.*;
class App76
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
OutputStream out=new FileOutputStream(yck[1]);
int n;
n=inp.read();
while(n!=-1)
{
out.write(n);
n=inp.read();
}
inp.close();
out.close();
}
}
import java.io.*;
class App77
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
OutputStream out=new FileOutputStream(yck[1]);
byte x[]=new byte[inp.available()];
inp.read(x);
out.write(x);
inp.close();
out.close();
}
}


output:

\>javac App77.java
\>java App77 App77.java sample.txt
\>type sample.txt
import java.io.*;
class App77
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
OutputStream out=new FileOutputStream(yck[1]);
byte x[]=new byte[inp.available()];
inp.read(x);
out.write(x);
inp.close();
out.close();
}
}
import java.io.*;
class App78
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
OutputStream out=new FileOutputStream(yck[1]);
byte x[]=new byte[inp.available()];
inp.read(x);
out.write(x,0,200);
inp.close();
out.close();
}
}


output:

\>javac App78.java
\>java App78 App78 sample.txt
import java.io.*;
class App78
{
public static void main(String yck[]) throws IOException
{
InputStream inp=new FileInputStream(yck[0]);
OutputStre

DataInputStream class:
         Allows you to create an ‘InputStream’ for the standard input device.

Constructor:
DataInputStream(InputStream object);
Method:

  1. String readLine(); Reads the line of text.
import java.io.*;
class App79
{
public static void main(String yck[]) throws IOException
{
DataInputStream cin=new DataInputStream(System.in);
int x,y,sum;
System.out.println("Enter the first number :");
x=Integer.parseInt(cin.readLine());
System.out.println("Enter the second number :");
y=Integer.parseInt(cin.readLine());
sum=x+y;
System.out.println("Sum of numbers :"+sum);
}
}


output:

\>javac App79.java
Note: App79.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.

\>java App79
Enter the first number :
10
Enter the second number :
20
Sum of numbers :30


import java.io.*;
class App80
{
public static void main(String yck[]) throws IOException
{
DataInputStream cin=new DataInputStream(System.in);
int sno,m1,m2,m3,total;
double avg;
String sname;
System.out.println("Student's no :");
sno=Integer.parseInt(cin.readLine());
System.out.println("Student's name :");
sname=cin.readLine();
System.out.println("Marks in subject I:");
m1=Integer.parseInt(cin.readLine());
System.out.println("Marks in subject II :");
m2=Integer.parseInt(cin.readLine());
System.out.println("Marks in subject III :");
m3=Integer.parseInt(cin.readLine());
total=m1+m2+m3;
avg=total/3;
System.out.println("Total marks :"+total);
System.out.println("Avg. marks :"+avg);
}
}


output:

\>javac App80.java
Note: App80.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.

\>java App80
Student's no :
1
Student's name :
chaitanya
Marks in subject I:
15
Marks in subject II :
20
Marks in subject III :
22
Total marks :57
Avg. marks :19.0

DataOutputSream:
         Allows you to create an output stream for the standard output device.

Constructor:

  1. DataOutputStream(output stream object);

Method:

  1. void writeLine(String str); writes the line of text to the standard output device.

    Example:

    DataOutputStream cout = new DataOutputStream(System.out);
    Cout.writeLine(“Hello World”);

ByteArrayInputStream:
         The “ByteArrayInputStream” is an implementation of an inputstream that uses a byte array as the source.

Constructor:

  1. ByteArrayInputStream(byte array[]);
  2. ByteArrayInputStream(byte array[], int offset, int numbytes);
import java.io.*;
class App81
{
public static void main(String args[]) throws IOException
{
InputStream inp=new FileInputStream(args[0]);
byte x[]=new byte[inp.available()];
inp.read(x);
inp.close();
ByteArrayInputStream bin=new ByteArrayInputStream(x);
int n;
n=bin.read();
while(n!=-1)
{
System.out.print((char)n);
n=bin.read();
}
bin.close();
}
}


output:

\>javac App81.java
\>java App81 App81.java
import java.io.*;
class App81
{
public static void main(String args[]) throws IOException
{
InputStream inp=new FileInputStream(args[0]);
byte x[]=new byte[inp.available()];
inp.read(x);
inp.close();
ByteArrayInputStream bin=new ByteArrayInputStream(x);
int n;
n=bin.read();
while(n!=-1)
{
System.out.print((char)n);
n=bin.read();
}
bin.close();
}
}

ByteArrayOutputStream Class:
         The ” ByteArrayOutputStream” class is an implementation of an output stream that uses a byte array as a destination.

Constructor:
ByteArrayOutputStream(); In the first form, creates the buffer of 32 bytes.ByteArrayOutputStream(int numbytes); In the second form, creats a buffer with the size equal to “numbytes”.

Note: The buffer is held in a protected field “buf” of the ” ByteArrayOutputStream” object. The buffer size is automatically increased when needed.

Methods:

  1. byte[] toByteArray(); write the contents of the “ByteArrayOutputStream” object into the byte array.
  2. Void writeTo(OutputStream object); Allows you to write the contents of another output stream object stream such as a file.
import java.io.*;
class App82
{
public static void main(String args[]) throws IOException
{
String s=new String("Hello World");
byte buffer[]=s.getBytes();
ByteArrayOutputStream out=new ByteArrayOutputStream();
out.write(buffer);
byte x[]=out.toByteArray();
System.out.println("Printing the contents of x ...");
for(int i=0;i System.out.print((char)x[i]);
FileOutputStream fos=new FileOutputStream(args[0]);
out.writeTo(fos);
out.close();
fos.close();
}
}


output:

\>javac App82.java
\>java App82 sample.txt
Printing the contents of x ...
Hello World
\>type sample.txt
Hello World