0% found this document useful (0 votes)
148 views22 pages

Java IO Stream

1. Java performs input and output through streams which are linked to physical devices. There are two types of streams: byte streams for input/output of bytes and character streams for input/output of characters. 2. Byte streams have input and output stream classes like FileInputStream and FileOutputStream. Character streams have reader and writer classes like FileReader and FileWriter. 3. Reading input in Java can be done through classes like BufferedReader while writing output uses PrintStream classes and their print(), println() and write() methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
148 views22 pages

Java IO Stream

1. Java performs input and output through streams which are linked to physical devices. There are two types of streams: byte streams for input/output of bytes and character streams for input/output of characters. 2. Byte streams have input and output stream classes like FileInputStream and FileOutputStream. Character streams have reader and writer classes like FileReader and FileWriter. 3. Reading input in Java can be done through classes like BufferedReader while writing output uses PrintStream classes and their print(), println() and write() methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

Java IO Stream

Java performs I/O through Streams. A Stream is linked to a physical layer by java


I/O system to make input and output operation in java. In general, a stream means
continuous flow of data. Streams are clean way to deal with input/output without
having every part of your code understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of
streams. They are,

1. Byte Stream : It provides a convenient means for handling input and output
of byte.
2. Character Stream : It provides a convenient means for handling input and
output of characters. Character stream uses Unicode and therefore can be
internationalized.

Java Byte Stream Classes


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.

Some important Byte stream classes.

Stream class Description


BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data ty

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are

1. read() : reads byte of data.


2. write() : Writes byte of data.

Java Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy,
they are Reader and Writer.
These two abstract classes have several concrete classes that handle unicode
character.

Some important Charcter stream classes

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.


Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Reading Console Input


We use the object of BufferedReader class to take inputs from the keyboard.

Reading Characters
read() method is used with BufferedReader object to read characters. As this
function returns integer type value has we need to use typecasting to convert it
into char type.
int read() throws IOException

Below is a simple example explaining character input.


class CharRead

public static void main( String args[])

BufferedReader br = new Bufferedreader(new


InputstreamReader(System.in));
char c = (char)br.read(); //Reading character

Reading Strings in Java


To read string we have to use readLine() function with BufferedReader class's
object.
String readLine() throws IOException

Program to take String input from Keyboard in Java

import java.io.*;

class MyInput

public static void main(String[] args)

String text;

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

text = br.readLine(); //Reading String

System.out.println(text);

Writing Console Output in Java


Writing Console Output in Java refers to writing the output of a Java program to the console
or any particular file.
The methods used for streaming output are defined in the PrintStream class. The methods
used for writing console output are print(), println() and write().

Methods of Writing Console Output in


Java-print() and println()
Both print() and println() methods are used to direct the output to the console. These methods
are defined in the PrintStream class and are widely used. Both these methods are used with
the help of the System.out stream.

The basic differences between print() and println() methods are as follows:

 print() method displays the string in the same line


whereas println() method outputs a newline character
after its execution.
 print() method is used for directing output to console
only whereas println() method is used for directing
output to not only console but other sources also.

Now, let us understand it in a better way with the help of some examples.

Example of print() method:

  
 
1. // Sample program to display numbers from 1-10
using print method
2. class printEg
3. {
4.             public static void main(String args[])
5.             {
6.                         int a;
7.                         for (a=1 ;  a<=10 ;  a++)
8.                         {
9.                                    
System.out.print(a);
10.                         }
11.             }
12. }

Output:
Example of println() method:

Let us take the same example above and use println() method in place of print() method.

  
 
1. // Sample program to display numbers from 1-10
using println method
2. class printlnEg
3. {
4.             public static void main(String args[])
5.             {
6.                         int a;
7.                         for (a=1 ; a<=10 ; a++)
8.                         {
9.                                  
System.out.println(a);
10.                         }
11.             }
12. }

Output:

Observe the difference in the output.

Both these functions work best for output of strings as well. Let us have a look at another
example.

Displaying strings using print() and println() methods


It is very easy to display strings using print() and println() methods. For displaying any
particular string, the string to be displayed on screen is written within the double quotation
marks (i.e. “  “).

For example:     System.out.println(“Hello!! How are you?”);

In addition, if you want to display the value of any particular variable used in the program,
then you have to append the variable name along with the string with a plus (+) symbol.

Example for displaying any string output:

  
 
1. // Sample program to display sum of numbers from 1-
10
2. class Eg1
3. {
4.             public static void main(String args[])
5.             {
6.                         int a, total = 0;
7.                         for (a=1 ; a<=10 ; a++)
8.                         {
9.                                     total = total +
a;
10.                         }
11.                        
System.out.println("Sum of first 10 numbers is: " +
total);
12.             }
13. }

Output:
The write() method
Alternatively, you can make use of the write() method for directing the output of your
program to the console. The easiest syntax of the write() method is:

void write(int b);

Where b is an integer of low order eight bits.

Let us have a look at a simple example.

  
 
class writeEg
{
            public static void main(String args[])
            {
                        int a, b;
                        a = 'Q';
                        b = 65;
                      System.out.write(a);
                      System.out.write('\n');
                       System.out.write(b);
                        System.out.write('\n');
            }
}

Output:

The Predefined Streams


As you know, all Java programs automatically import the java.lang package. This
package defines a class called System, which encapsulates several aspects of the
run-time environment.
For example, using some of its methods, you can obtain the current time and the
settings of various properties associated with the system. System also contains
three predefined stream variables: in, out, and err. These fields are declared as
public, static, and final within System. This means that they can be used by any
other part of your program and without reference to a specific System object.
System.out refers to the standard output stream. By default, this is the console.
System.in refers to standard input, which is the keyboard by default. System.err
refers to the standard error stream, which also is the console by default. However,
these streams may be redirected to any compatible I/O device.
System.in is an object of type InputStream; System.out and System.err are objects
of type PrintStream. These are byte streams, even though they typically are used to
read and write characters from and to the console. As you will see, you can wrap
these within character basedstreams, if desired.
The preceding chapters have been using System.out in their examples. You can use
System.err in much the same way.

Java Serialization and


Deserialization
Serialization is a process of converting an object into a sequence of bytes which
can be persisted to a disk or database or can be sent through streams. The reverse
process of creating object from sequence of bytes is called deserialization.
A class must implement Serializable interface present in java.io package in order
to serialize its object successfully. Serializable is a marker interface that adds
serializable behaviour to the class implementing it.
Java provides Serializable API encapsulated under java.io package for serializing
and deserializing objects which include,

 java.io.serializable

 java.io.Externalizable

 ObjectInputStream

 ObjectOutputStream

Java Marker interface


Marker Interface is a special interface in Java without any field and method. Marker
interface is used to inform compiler that the class implementing it has some special
behaviour or meaning. Some example of Marker interface are,

 java.io.serializable

 java.lang.Cloneable

 java.rmi.Remote

 java.util.RandomAccess
All these interfaces does not have any method and field. They only add special
behavior to the classes implementing them. However marker interfaces have been
deprecated since Java 5, they were replaced by Annotations. Annotations are used
in place of Marker Interface that play the exact same role as marker interfaces did
before.
To implement serialization and deserialization, Java provides two classes
ObjectOutputStream and ObjectInputStream.
while serializing if you do not want any field to be part of object state then declare it
either static or transient based on your need and it will not be included during java
serialization process.
Serialization is the process of writing the state of an object to a byte stream. This is
useful when you want to save the state of your program to a persistent storage area,
such as a file. At a later time, you may restore these objects by using the process of
deserialization. Serialization is also needed to implement Remote Method Invocation
(RMI). RMI allows a Java object on one machine to invoke a method of a Java object
on a different machine. An object may be supplied as an argument to that remote
method. The sending machine serializes the object and transmits it. The receiving
machine deserializes it.

Java Enumerations
Enumerations was added to Java language in JDK5. Enumeration means a list of
named constant. In Java, enumeration defines a class type. An Enumeration can
have constructors, methods and instance variables. It is created
using enum keyword. Each enumeration constant is public, static and final by
default. Even though enumeration defines a class type and have constructors, you
do not instantiate an enum using new. Enumeration variables are used and declared
in much a same way as you do a primitive variable.
How to Define and Use an Enumeration
1. An enumeration can be defined simply by creating a list of enum variable. Let
us take an example for list of Subject variable, with different subjects in the list.
2. //Enumeration defined

3. enum Subject

4. {

5. Java, Cpp, C, Dbms

6. Identifiers Java, Cpp, C and Dbms are called enumeration constants. These


are public, static and final by default.
7. Variables of Enumeration can be defined directly without any new keyword.

Example of Enumeration
Lets create an example to define an enumeration and access its constant by using
enum reference variable.
enum WeekDays{

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY

class Demo

public static void main(String args[])

WeekDays wk; //wk is an


enumeration variable of type WeekDays

wk = WeekDays.SUNDAY; //wk can be assigned


only the constants defined under enum type Weekdays
System.out.println("Today is "+wk);

Today is SUNDAY

Example : Enumeration in If-Else


Enumeration can be used in if statement to compare a value with some predefined
constants. Here we are using an enumeration with if else statement.

enum WeekDays{

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY

class Demo {

public static void main(String args[])

WeekDays weekDays = WeekDays.WEDNESDAY;

if(weekDays == WeekDays.SUNDAY || weekDays ==


WeekDays.SATURDAY)

System.out.println("It is Weekend");

else

System.out.println("It is weekday:
"+weekDays);

}
It is weekday: WEDNESDAY

Example: Traversing Enumeration Elements


We can iterate enumeration elements by calling its static method values(). This
method returns an array of all the enum constants that further can be iterate using
for loop. See the below example.

enum WeekDays{

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY

class Demo {

public static void main(String args[])

WeekDays[] wk = WeekDays.values();

for(WeekDays weekday : wk ){

System.out.println(weekday);

}
SUNDAY

MONDAY

TUESDAY

WEDNESDAY

THURSDAY

FRIDAY

SATURDAY

Values() and ValueOf() method


All the enumerations predefined methods values() and valueOf(). 
values() method returns an array of enum-type containing all the enumeration
constants in it. Its general form is,
public static enum-type[ ] values()

valueOf() method is used to return the enumeration constant whose value is equal


to the string passed in as argument while calling this method. It's general form is,
public static enum-type valueOf (String str)

Example of enumeration using values() and valueOf()


methods:
Value and valueOf both are static methods of enum type and can be used to access
enum elements. Here we are using both the methods to access the enum elements.

enum Restaurants {

DOMINOS, KFC, PIZZAHUT, PANINOS, BURGERKING

class Demo {

public static void main(String args[])

Restaurants r;

System.out.println("All constants of enum type


Restaurants are:");

Restaurants rArray[] = Restaurants.values();


//returns an array of constants of type Restaurants
for(Restaurants a : rArray) //using foreach loop

System.out.println(a);

r = Restaurants.valueOf("DOMINOS");

System.out.println("It is " + r);

r = Restaurants.valueOf("DOMINOS");

System.out.println("It is " + r);

int i= Restaurants.KFC.ordinal();

System.out.println("Value is " + i);

All constants of enum type Restaurants are:

KFC

PIZZAHUT

PANINOS

BURGERKING

It is DOMINOS

enum ordinal()

The ordinal() method returns the order of an enum instance. It represents


the sequence in the enum declaration, where the initial constant is assigned an
ordinal of '0'. It is very much like array indexes.
Restaurants.KFC.ordinal(); // 1

Restaurants.DOMINOS.ordinal(); // 0
Autoboxing and Unboxing in Java
Java added concept of autoboxing and unboxing that deal with conversion of
primitive type to object and vice versa.
The term autoboxing refers to the auto conversion of primitive type to its
correspond object type. For example, conversion of int type to Integer object or char
type to Character object. This conversion is done implicitly by the Java compiler
during program execution.
In the same context, when an object coverts to its correspond primitive type then it is
called unboxing. For example, conversion of Integer type to int type or Byte to byte
type etc. Java automatically performs this conversion during program execution.

Example of Autoboxing
In this example, we are assigning an int type value to Integer object and notice
compiler does not report any error because it performs autoboxing here.

class Demo

public static void main(String[] args)

Integer i = 100; // Auto-boxing of int i.e


converting primitive data type int to a Wrapper class Integer

System.out.println(i);

Character ch = 'a';

System.out.println(ch);

Byte b = 12;

System.out.println(b);

}
100

12

Explanation:
Whenever we use object of Wrapper class in an expression, autoboxing is done by
JVM.
This will happen always, when we will use Wrapper class objects in expressions or
conditions etc.

Example : Unboxing
In this example, we using arraylist to store int type values. Since arraylist stores only
object then it automatically converts int type to Integer and store the elements. If we
fetch the elements of it returns object type and if we store it into primitive int type
then it automatically converts Integer to int type. See the below example.

import java.util.ArrayList;

class Demo

public static void main(String[] args)

ArrayList arrayList = new ArrayList();

arrayList.add(100); // autoboxing int to Integer

arrayList.add(200);

arrayList.add(300);

for(Integer i : arrayList) {

System.out.println(i);

// unboxing Integer to int type


int first = arrayList.get(0);

System.out.println("int value "+first);

100

200

300

int value 100

Integer iOb = 100; // autobox an int


Notice that no object is explicitly created through the use of new. Java handles this
for you,automatically.
To unbox an object, simply assign that object reference to a primitive-type variable.
For example, to unbox iOb, you can use this line:
int i = iOb; // auto-unbox
Java handles the details for you.
Here is the preceding program rewritten to use autoboxing/unboxing:
// Demonstrate autoboxing/unboxing.
class AutoBox {
public static void main(String args[]) {
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb); // displays 100 100
}
}

Java Console Class


The Java Console class is be used to get input from console. It provides methods to
read texts and passwords.

If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally.

Java Console class methods

String readLine() It is used to read a single line of text from the console.

char[] readPassword() It is used to read password that is not being displayed on the console.

Java Console Example


import java.io.Console;  
class ReadStringTest{    
public static void main(String args[]){    
Console c=System.console();    
System.out.println("Enter your name: ");    
String n=c.readLine();    
System.out.println("Welcome "+n);    
}    
}  

Java Console Example to read password


import java.io.Console;  
class ReadPasswordTest{    
public static void main(String args[]){    
Console c=System.console();    
System.out.println("Enter password: ");    
char[] ch=c.readPassword();    
String pass=String.valueOf(ch);//converting char array into string    
System.out.println("Password is: "+pass);    
}    
}  

Generics in Java
It would be nice if we could write a single sort method that could sort the elements
in an Integer array, a String array, or an array of any type that supports ordering.
Java Generic methods and generic classes enable programmers to specify, with a
single method declaration, a set of related methods, or with a single class
declaration, a set of related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch
invalid types at compile time.
Using Java Generic concept, we might write a generic method for sorting an array
of objects, then invoke the generic method with Integer arrays, Double arrays,
String arrays and so on, to sort the array elements.

Generic Methods
You can write a single generic method declaration that can be called with
arguments of different types. Based on the types of the arguments passed to the
generic method, the compiler handles each method call appropriately. Following are
the rules to define Generic Methods −
 All generic method declarations have a type parameter section delimited by
angle brackets (< and >) that precedes the method's return type ( < E > in
the next example).
 Each type parameter section contains one or more type parameters
separated by commas. A type parameter, also known as a type variable, is
an identifier that specifies a generic type name.
 The type parameters can be used to declare the return type and act as
placeholders for the types of the arguments passed to the generic method,
which are known as actual type arguments.
 A generic method's body is declared like that of any other method. Note that
type parameters can represent only reference types, not primitive types (like
int, double and char).

public class GenericMethodTest {


// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}

public static void main(String args[]) {


// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");


printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");


printArray(charArray); // pass a Character array
}
}

You might also like