eee unit v
DESCRIPTION
eeeTRANSCRIPT
-
1UNIT V - EXCEPTION HANDLING
Packages and Interfaces, Exception handling, Multithreaded programming, Strings,
Input/Output
PACKAGES
In java, package is the way of grouping a variety of classes and interfaces together. The package act as a container for classes.
Types of packages in Java
1. Java API Packages
2. User-defined Packages
JAVA API PACKAGES
Java API provides a large number of classes grouped into different packages according to their functionality.
PACKAGE NAME CONTENTSjava.lang Language support classes that are
automatically imported.They include classes for primitive types, strings, math functions etc.,
java.util Contains classes such as hash tables, vectors, random numbers and date etc.,
java.io They provide facilities for input/output support
java.awt Contains a set of classes for implementing graphical user interface.
java.net Contains classes for networkingjava.applet Contains classes for creating and
implementing applets
Java
util io awt net appletlang
-
2Using system packages
The classes of the package can be included in one or more programs by using the import statements at the top of the file.
import packagename.classname;or
import packagename.*;For example, the Color class in the awt package can be imported in two ways:
1. import java.awt.Color;or
2. import java.awt.*;
USER DEFINED PACKAGES
1. CREATING A PACKAGE
Syntax
package packagename;public class classname{
public returntype methodname(){.}}
Color
Font
Graphics
Image
java
awt
Package containing awt package
Package containing classes
Classes containing methods
-
3Steps for creating our own package:
1. Decide the name of the package.2. Create a folder(sub-directory) with the name of the package, where all the
source files are stored.3. Declare a package using the form:
package packagename;4. Define a class that is to be put inside the package and declare it as public.5. Store the file as classname.java inside the folder6. Switch to the folder,Compile the file. This creates .class file in the folder.7. Import the package in the other programs.
2. ACCESSING A PACKAGE
The general form of import statement for accessing a user-defined package is as follows:
import package1.[package2] .classname;
or
import package1.[package2].*;
Here package1 is the name of the top-level package, package2 is inside package1.
PACKAGE EXAMPLE
Create a folder pack1. The package named pack1 contains a single class class1.
Step 1: Creating the package
class1.java
package pack1; // package declarationpublic class class1 // Class defintion{
public void add(int a, int b){
int r1=a+b;System.out.println("The sum of two numbers:" +r1);
}public void sub(int a, int b){
int r2=a-b;System.out.println("The difference of two numbers:" +r2);
}
-
4public void mul(int a, int b){
int r3=a*b;System.out.println("The product of two numbers:" +r3);
}public void div(int a, int b){
int r4=a/b;System.out.println("The quotient of two numbers:" +r4);
}}Step 2 : Accessing the package in a program
Testpack.java
import pack1.*; // Accessing the package pack1.
class Testpack
{
public static void main(String arg[])
{
class1 ob=new class1(); // Object for the class defined inside pack1
ob.add(10,20); /*Invoking methods inside class1*/
ob.sub(20,10);
ob.mul(10,10);
ob.div(30,2);
}
}
Creating package with multiple classes:
1. Decide the name of the package.2. Create a folder with this name where the source files are stored.3. Create classes that are to be placed in the same package in separate source files and declare the package at the each class.
package packagename;4. Switch to the folder and compile each source file. Now, the package contain .class files for the source files.
==========================================================================
OUTPUT:The sum of two numbers:30The difference of two numbers:10The product of two numbers:100The quotient of two numbers:15
-
5INTERFACES: An interface is a collection of abstract methods and constant variables. A class implements an interface, thereby inheriting the abstract methods of the
interface.
In java, a subclass cannot have more than one superclass, but it can have more than one interface.
The concept of interface enables us to create classes without the problems created by multiple inheritance.
DEFINING AN INTERFACE:Syntax:
interface interfacename{
variable declaration;methods declaration;
}
Syntax for variable declaration:
final datatype variablename=value;Syntax for method declaration:
returntype methodname(parameter list);
Example:interface purchase{
final String prodname=Fan;final int cost=1500;void display();
}
EXTENDING INTERFACES: Like classes, interfaces can also be extended (inherited). This can be done by
using the extends keyword.
Syntax:
1.An interface can be extended from another interface
interface NAME2 extends NAME1
{
//declare final variables and abstract methods
}
Interface NAME1
Interface NAME2
-
62.An interface can be extended from two interfaces
interface NAME3 extends NAME1, NAME2
{
//declare final variables and abstract methods
}
IMPLEMENTING INTERFACES:
An interface can act as a superclass whose properties (final variables and abstract methods) are inherited by classes.
Syntax:
1.The abstract methods and final variables of an interface can be implemented in a class by using the following syntax
class NAME2 implements NAME1
{
//define the class
}
2. In java, a subclass cannot have more than one superclass, but it can have more than one interface, implemented as follows:
class NAME3 implements NAME1,NAME2
{
//define the class
}
3. A subclass can be inherited from a class and interface as follows
class NAME3 extends NAME1 implements NAME2
{
//define the class
}
Interface NAME1
Interface NAME2
Interface NAME3
Interface NAME1
Class NAME2
Interface NAME1
Interface NAME2
Class NAME3
Class NAME1
Interface NAME2
Class NAME3
-
7EXAMPLE: IMPLEMENTING MULTIPLE INHERITANCE USING INTERFACES
In java, a subclass cannot have two superclasses but it can be inherited from multiple interfaces or a subclass can be inherited from one super class and one interface.
In this hierarchy, the result class has two parents. One is the test class and the other is an interface named sports. The following program illustrates the use of interface to substitute multiple inheritance in java.
//PROGRAM : hybrid.javaclass roll{
int rollno;void getroll(int a){
rollno=a;}void putroll(){
System.out.println("Roll no: "+rollno);}
}class test extends roll{
int m1,m2;void getmark(int x, int y){
m1=x;m2=y;
}void putmark(){
System.out.println("Marks obtained");System.out.println("Mark 1=" +m1);System.out.println("Mark 2=" +m2);
}}
Class roll
Class result
Class test Interface sports
-
8interface sports{
final float credit=10.5F; // Final variable declaredvoid putcredit(); //Abstract method declared
}class result extends test implements sports{
float total;public void putcredit(){
total=m1+m2+credit;putroll();putmark();System.out.println("Sports credit:" + credit);System.out.println("Total score:" +total);
}}class hybrid{
public static void main(String arg[]){
result ob=new result();ob.getroll(101);ob.getmark(90,95);ob.putcredit();
}}
----------------------------------------------------------------------------------------------------------DIFFERENCE BETWEEN CLASS AND INTERFACENo CLASS INTERFACE1 The variables of the class can be
constant or variableThe variables of an interface are always declared as constant. i.e their values are final.
2 The class definition can contain method definition. The methods can be abstract or non-abstract
The methods in an interface must be abstract. These methods are defined by the class that implements the interface
3 Objects can be created Objects cannot be created. It can only be inherited
4 It can use access specifiers like public, private or protected
It can only use the public access specifier
OUTPUT
Roll no: 101Marks obtainedMark 1=90Mark 2=95Sports credit:10.5Total score:195.5
-
9DIFFERENCE BETWEEN INTERFACE AND ABSTRACT CLASS
No INTERFACE ABSTRACT CLASS 1 Interface contains abstract methods
and cannot have implementations Abstract class can have methods with implementation and abstract methods without implementations
2 Variables of a interface are final Variables of an abstract class may contain non-final variables
3 Members of an interface are public by default
Members of a abstract class can be public, private, protected etc.,
4 A class can implement multiple interfaces
A class can extend only one abstract class
5 Interfaces are slower compared to abstract class due to extra indirection
Faster than interfaces.
=======================================================================EXCEPTION HANDLING
An exception is a condition caused by a run-time error in the program. When the java interpreter encounters a runtime error, it creates an exception
object and throws it to the handler.
Tasks performed by the error handling code:1. Find the problem (Hit the exception)2. Inform that an error has occurred (Throw the exception)3. Receive the error information(Catch the exception)4. Take corrective actions (Handle the exception)
COMMON EXCEPTIONS IN JAVA
Sno EXCEPTION TYPE CAUSE OF EXCEPTION1 ArithmeticException Caused by math errors such as division by
zero2 ArrayIndexOutOfBoundsException Caused by bad array indexes
3 ArrayStoreException Caused when a program tries to store the wrong type of data in an array.
4 FileNotFoundException Caused by an attempt to open a file that does not exist.
5 IOException Caused by general I/O failures, such as inability to read or write from the file
6 NumberFormatException Caused when a conversion between strings and number fails
7 OutOfMemoryException Caused when there is not enough memory to allocate a new object
8 SecurityException Caused when an applet tries to perform an action that is not allowed by browsers security setting
-
10
9 StackOverFlowException Caused when the system runs out of stack space
10 StringIndexOutOfBoundsException Caused when a program attempts to access a non-existent character position in a string
CATEGORIES OF EXCEPTIONS IN JAVA
1. CHECKED EXCEPTIONS These exceptions are explicitly handled in the code with the help of try-
catch blocks. Checked exceptions are extended from the Exception class of the lang
package. (i.e) java.lang.Exception
2. UNCHECKED EXCEPTIONS These exceptions are not handled in the program code, instead the JVM
handles such exceptions. Unchecked exceptions are extended from the RunTimeException class
of the lang package. (i.e) java.lang.RunTimeException
BASIC CONCEPT OF EXCEPTION HANDLING
The basic concepts of exception handling are throwing an exception and catching it.
Syntax of try - catch block:
try{ //Statements that generates exceptions}catch(Exception-type e){
//Statements that processes the exception}
try block
Statements that causes an exception
catch block
Statements that handles the exception
Exception object creator
Exception handler
Throws exception object
-
11
Try block: Try block contains code that is likely to cause an error condition and throw an
exception
Catch block: The catch block catches the exception thrown by the try block and handles it
appropriately.Example 1: Try-Catch block for exception handling
Error2.java
class Error2{
public static void main(String arg[]){
int a=10;int b=5;int c=5;int x,y;try{
x=a/(b-c);System.out.println("x=" +x);
}catch(ArithmeticException e){
System.out.println("Division by zero");}y=a/(b+c);System.out.println("y=" + y);
}}
While executing this program, the program did not stop at the point when exception is raised.
The Exception is found, handled and then the program continued its execution. If the same code has been executed without try-catch blocks, then the program
would have terminated after displaying runtime errors.
OUTPUT:
Division by zero
y=1
-
12
MULTIPLE CATCH BLOCKSSyntax:
try{
//statement that generates an exception}catch( Exceptiontype1 e){
// Statements that processes the exceptiontype1}catch( Exceptiontype2 e){
// Statements that processes the exceptiontype2}EXAMPLE: EXCEPTION HANDLING USING MULTIPLE CATCH BLOCKS
Error3.javaclass Error3{
public static void main(String arg[]){
int a[ ]={5,10};int b=5;try{
int x=a[2]/b-a[1];System.out.println(x= +x);
}catch(ArithmeticException e){
System.out.println("Division by zero error");}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array Index Error");}catch(ArrayStoreException e){
System.out.println("Wrong Data Type");}int y=a[1]/a[0];System.out.println(y=+y);
}}
The array element a[2] does not exist because the array a has only two elements with indexes a[0] and a[1].
OUTPUT:
Array Index Error
y=2
-
13
Index a[2] is outside the array boundary, thus raising ArrayIndexOutOfBoundsException.
This exception is handled by catch(ArrayIndexOutOfBoundsException e) Remaining catch blocks are skipped from execution.
THROWS If a method is capable of causing an exception that it does not handle, then the
throws clause is used in the method definition statement to guard them against the exception.
A throws keyword lists the types of exceptions that a method might throw.Example: throwseg.javaclass throwseg{static void divide() throws ArithmeticException{
int x=22, y=0,z;z=x/y;
}public static void main(String arg[]){
try{divide();}catch(ArithmeticException e){
System.out.println("Caught the exception:" +e);}
}}OUTPUT:Caught the exception:java.lang.ArithmeticException: / by zero
FINALLY BLOCK The finally block may be added immediately after the try block or after the try
block or after the last catch block. When a finally block is defined, this is guaranteed to execute, whether or not
an exception is thrown.Syntax:
try{
//statement that generates an exception}
-
14
catch( Exceptiontype1 e){
// Statements that processes the exceptiontype1}catch( Exceptiontype2 e){
// Statements that processes the exceptiontype2}finally{}
THROWING OWN EXCEPTIONS
Two steps are involved for throwing own exceptions1. Define a class that extends from the Exception class2. Define a subclass constructor inside this class to handle the error message by
invoking the super class (Exception class) constructor with super call.
Example:
Write a java program to add two numbers, if the numbers are in the range 0 to 9.If this condition is violated, display an error message on the screen.
import java.util.*;import java.lang.Exception;
class Newexception extends Exception //Defining subclass for Exception class{
Newexception(String message){
super(message);}
}class testmine{public static void main(String arg[])
{System.out.println("Enter the first number");Scanner in1=new Scanner(System.in);int x = in1.nextInt(); //Gets runtime input as integer
System.out.println("Enter the Second number");Scanner in2=new Scanner(System.in);int y = in2.nextInt(); //Gets runtime input as integer
int z;
-
15
try //Checking whether the given number is 0 - 9{if((x=9)) {
Newexception e= new Newexception(The number should be in range 0 to 9");throw e; //Throws exception object to the handler
}else if((y=9)) {
Newexception e= new Newexception("The number should be in range 0 to 9");throw e; //Throws exception object to the handler
}else{
z=x+y;System.out.println("Result=" +z);
}} //End of try blockcatch(Newexception e) // Catch block to handle own exception{
System.out.println(e);}finally{
System.out.println("Execution over");}
} //End of main()} //End of classOUTPUT:First runEnter the first number5Enter the Second number5Result=10Execution over
Second run
Enter the first number5Enter the Second number15Newexception: The number should be in range 0 to 9Execution over
=======================================================================
-
16
MULTITHREADINGThread:
A thread is similar to a program that has a single flow of control. It has a beginning, a body and an end and executes commands sequentially.MULTITHREADING
Multithreading is a conceptual programming paradigm where a program is divided into two or more sub-programs which can be implemented at the same time in parallel.
Multithreading is a unique property of Java. A program that contains multiple flow of control is known as multithreaded
program.Structure of Multithreaded program:
The above java program contains four threads. One main thread and three other threads.
During execution, the main thread and the other threads A,B & C run concurrently and share the resources.
Since threads in Java are subprograms of the main application program and share the same memory space, they are known as lightweight threads.
Since all the threads are running on a single processor, the flow of execution is shared between threads.
The Java interpreter handles the switching of control between the threads in such a way that it appears like they run concurrently.
Mutlithreading enables the programmer to do multiple things at one time. For example, we can send printing tasks into background and continue editing
the word document in foreground. This considerably improves the speed of our operation.
Main Thread
Thread A Thread B Thread C
Start Start Start
Switching Switching
-
17
CREATING THREADSThreads can be created in two ways:
1. By extending the Thread class.2. By implementing the Runnable Interface.
*1.CREATING THREADS BY EXTENDING THE THREAD CLASS.
The process for thread creation involves 3 steps:
Step1: Define a class that extends(inherits) from the Thread classSyntax:
class mythread extends Thread{
}Here, Thread is the predefined class of the lang package, to implement multithreading process in Java
Step 2: Implement the run() method The run() is the main portion of any thread. Using this run() method the
threads can be implemented. The run() method has been inherited from Thread class and overridden to
implement the code to be executed by our thread.Syntax:
class mythread extends Thread{
...public void run(){//statements implemented for thread....}
}Step 3: Start the thread
Create an object for the user-defined thread class defined above. Start the threads inside the main() function
Syntax:
mythread ob=new mythread();
ob.start();
The start() method is used to invoke the run() method defined inside the class. So,
the thread starts its execution and becomes active after run() method is invoked.
-
18
*2.CREATING THREADS BY IMPLEMENTING THE RUNNABLE INTERFACE1. Create a class that implements the Runnable interface
2. Provide the run() method that will be executed by the thread. An object of this
class is a Runnable object.
3. An object of Thread class is created by passing a Runnable object as
argument to the Thread constructor. The Thread object now has a Runnable
object that implements the run() method.
4. The start() method is invoked on the Thread object created in the previously.
----------------------------------------------------------------------------------------------------------EXAMPLE : CREATING THREADS USING THREAD CLASS
class A extends Thread{
public void run(){
for(int i=1; i
-
19
class Threadtest{
public static void main(String arg[]){
A ob1=new A();B ob2=new B();C ob3=new C();ob1.start();ob2.start();ob3.start();
}}
The output for the multithreaded program is not sequential. They do not follow any specific order.
Once the thread has started, we cannot decide the flow of executing the statements. There interpreter plays the role of switching between threads.
LIFE CYCLE OF THREAD
The life cycle of a thread includes 5 states1. Newborn state2. Runnable state3. Running state4. Blocked state5. Dead state
STATE DIAGRAM SHOWING THREAD LIFE CYCLE
-
20
1. NEWBORN STATE
When we create a thread object, it is said to be in newborn state. The thread is not scheduled for being executed. At this state, one of the two things can happen.
i. Schedule it for running using start() method.ii. Kill it using stop() method.
If the start() method is called the thread moves to the runnable state.
2. RUNNABLE STATE
In the runnable state, the thread is ready for execution and is waiting for the availability of the processor.
The threads have joined the queue of threads that are waiting for execution. It will be served in first-come, first-serve manner.
If we want a thread to relinquish(give up) control to another thread, yield() method is used.
-
21
3. RUNNING STATE In this state, the processor has given its time for execution to the threads
waiting in the queue. A running thread can relinquish( give up) its control in any of the following
situationsCase 1: suspend()
It can be suspended using the suspend() method. The suspended thread can be re-invoked by using the resume() method. This approach is useful when we want to block the thread for sometime,
but not want to kill it.
Case 2: sleep(time) An active thread can be put to sleep for a specified time period, where the
time is in milliseconds. The thread is out of the runnable queue for this time period. After the specified time, the thread re-enters the runnable state.
Case 3: wait() An active can be told to wait until some occurs. This is done by using the wait()
method. The notify() method schedules to run the thread again.
-
22
4. BLOCKED STATE A thread is said to be in blocked state, when it is prevented from entering
into the runnable state and then the running state. This happens when the thread is subject to suspend, sleep or wait. A blocked thread is not runnable , not dead.
5. DEAD STATE A running thread will be destroyed when it has completed the execution of
run() method. The thread can also be destroyed voluntarily by use of stop() method. The thread that can be destroyed using the stop() method in either new born
state, active or blocked state.EXAMPLE USING THREAD METHODSclass A extends Thread{
public void run(){
for(int i=1; i
-
23
catch(Exception e){System.out.println(e);}
}
}}
}class Threadmethod{
public static void main(String arg[]){
A ob1=new A();B ob2=new B();C ob3=new C();ob1.start();ob2.start();ob3.start();
}}
This program used the yield() method in thread A. Although thread A started first, it will give up its control to thread B.
The stop() method in thread B kills the thread. The sleep() method in thread C, started sleeping when k==1. After 1000
milliseconds, it will wake up and continue its execution. During this sleeping
period thread A will be executed.
Thread priority
The threads of same priority are given equal treatment by the java scheduler. So, they share the processor in first-come first-serve basis.
Java also permits to set the priority of a thread using setPriority() method.Syntax:
threadobject. setpriority (integer number);
The Thread class defines several priority constants:o MIN_PRIORITY = 1
o NORM_PRIORITY=5
o MAX_PRIORITY=10
OUTPUT:From Thread B, j=1From Thread B, j=2From Thread B, j=3From Thread C, K=1From Thread A, i=1From Thread A, i=2From Thread A, i=3From Thread A, i=4From Thread A, i=5From Thread C, K=2From Thread C, K=3From Thread C, K=4From Thread C, K=5
-
24
SYNCHRONIZATION
When two or more threads need access to a shared resource (file or memory), they need some way to ensure that the resource will be used by only one thread at a time.
The process by which this synchronization is achieved is called thread synchronization.
For example, Consider that one thread may try to read from the file, while another thread is still writing to the same file.
Here, conflict occurs. The read process ends with wrong result by reading the old entries of the file.
To overcome this problem, java enables a technique known as synchronization.
The keyword synchronized is used while declaring both the read() and write() functions.
Syntaxclass A extends Thread{
public void run(){
synchronized void read(){
// Read from the file}
}}class B extends Thread{
public void run(){
synchronized void write(){
// Write contents to the file}
}}
When a method is declared as synchronized, Java creates a monitor and hands it over to the thread that calls the method first.
As long as the thread holds the monitor, no other thread can enter into the synchronized section.
=======================================================================
-
25
STRINGSStrings represent a sequence of characters. In java, strings are the class objects and implemented using two classes
i) Stringii) StringBuffer
A java string is not a character array and is not NULL terminated.
Declaring A String Object:
----------------------------------------------------------------------------------------------------------JAVA PROGRAM TO PERFORM STRING MANIPULATIONS----------------------------------------------------------------------------------------------------------stringmanip.javaclass stringmanip
{
public static void main(String arg[])
{
String s1="HelloEEE";
String s2;
System.out.println("Original string:" + s1);
// 1. COnverting string to lower case
s2=s1.toLowerCase();
System.out.println("1. Small case string:" + s2);
//2. COnverting to upper case
String s3;
s3=s1.toUpperCase();
System.out.println("2. Upper case string:" + s3);
//3. Replace a character by another
String s4;
s4=s1.replace('H','h');
System.out.println("3. String Replace:" + s4);
String stringname=new String(Text); (or)
String stringname(Text);
-
26
// 4. Checking if strings are equal
System.out.print("4. Equals method:");
if(s1.equals(s2))
System.out.println("Strings are equal");
else
System.out.println("Strings are not equal");
// 5. Checking if strings are equal ignoring the case of characters.
System.out.print("5. Equals method by ignoring case of characters:" );
if(s1.equalsIgnoreCase(s2))
System.out.println("Strings are equal");
else
System.out.println("Strings are not equal");
// 6. Finding string length
int l=s1.length();
System.out.println("6. Length of the string:" + l);
// 7. Accessing characters in a strings
System.out.println("7. The character at position 2 is:" +s1.charAt(1));
// 8. Finding substring
s2=s1.substring(0,4);
System.out.println("8. Substring is of HelloEEE:" +s2);
// 9. Finding index
int pos=s1.indexOf('l');
System.out.println("9. The index of character 'l' is:" +pos);
// 10. Concatenation
System.out.println("10. Concatenated String:" + s1.concat(" Welcome"));
}
}
-
27
=====================================================================================
STREAMS AND I/O A stream in Java is a path along which data flows. It has a source and
destination In file processing, input refers to the flow of data into a program and output
means the flow of data out of a program.
Using input and output streams: Java streams are classified into basic types, input stream and output stream. Input stream extracts data from the source and sends it to the program Output stream takes data from the program and sends it to the destination.
OUTPUTOriginal string:HelloEEE
1. Small case string:helloeee
2. Upper case string:HELLOEEE
3. String Replace:helloEEE
4. Equals method:Strings are not equal
5. Equals method by ignoring case of characters:Strings are equal
6. Length of the string:8
7. The character at position 2 is:e
8. Substring is of HelloEEE:Hell
9. The index of character 'l' is:2
10. Concatenated String:HelloEEE Welcome
-
28
STREAM CLASSES IN JAVA The java.io package contains a large number of stream classes that is capable
for processing all the types of data. The java streams are categorized into two main categories
1. BYTE STREAM CLASSES
Provides support for managing I/O operations on bytes2. CHARACTER STREAM CLASSES
Provides support for managing I/O operations on characters. The source or destination may be a memory, a file and a pipe.
CLASSIFICATION OF JAVA STREAM CLASSES
BYTE STREAM CLASSES
The byte stream classes are used for creating and manipulating streams and files for reading and writing bytes.
Java provides two kinds of byte stream classes1. InputStream class
2. OutputStream class
Java Stream Classes
Byte Stream Classes Character Stream Classes
Input Stream Classes
Output Stream
Reader Classes
Writer Classes
Memory File Pipe Memory File Pipe
-
29
InputStream class
The input stream classes are used to read 8-bit bytes. It includes the super class known as InputStream
InputStream methods
Method Descriptionread() Reads a byte from the input streamread(byte b[]) Reads an array of bytes into bread(byte b[],int n,int m) Reads m bytes starting from nth byteskip(n) Skips over n bytes from the input streamreset() Goes back to the beginning of the streamclose() Closes the input stream
HIERARCHY OF INPUT STREAM CLASSES
Methods of DataInput Interface
The DataInputStream class extends (inherits) the FilterInputStream class and implements the interface DataInput.
The methods of DataInput interface are as follows:
1. readShort()
-
30
2. readInt()3. readLong()4. readFloat()5. readDouble()6. readLine()7. readChar()8. readBoolean()
OutputStream class
The output stream classes are used to write 8-bit bytes. It includes the super class known as OutputStream
OutputStream methods
Method Descriptionwrite() Writes a byte to the output streamwrite(byte b[]) Writes all bytes in the array b to the output streamwrite(byte b[], int n, int m) Writes m bytes of array b starting from nth byteclose() Closes the output streamflush() Flushes the output stream
HIERARCHY OF OUTPUT STREAM CLASSES
-
31
Methods of DataInput Interface
The DataOutputStream class extends (inherits) the FilterOutputStream class and implements the interface DataOutput.
The methods of DataOutput interface are as follows:1. writeShort()2. writeInt()3. writeLong()4. writeFloat()5. writeDouble()6. writeBytes()7. writeLine()8. writeChar()9. writeBoolean()
CHARACTER STREAM CLASSES
The character streams can be used to read and write 16-bit unicode characters. Java provides two kinds of byte stream classes
1.Reader Stream class 2.Writer Stream classReader Stream classes
The Reader class contains methods that are identical to InputStream class, but the Reader class is designed to handle character input.
-
32
Writer Stream classes
The Writer class contains methods that are identical to OutputStream class, but the Writer class is designed to handle character output.
LIST OF TASKS AND CLASSES IMPLEMENTING INPUT OPERATIONS
Tasks CharacterStream classes ByteStream classesPerform input operations Reader InputStreamBuffering input BufferedReader BufferedInputStreamKeeping track of line numbers
LineNumberReader LineNumberInputStream
Reading from an array CharArrayReader ByteArrayInputStreamReading from files FileReader FileInputStreamReading from a pipe PipedReader PipedInputStreamReading a String StringReader StringInputStreamReading primitive types None DataInputStream
LIST OF TASKS AND CLASSES IMPLEMENTING OUTPUT OPERATIONS
Tasks CharacterStream classes ByteStream classesPerform output operations Writer OutputStreamBuffering output BufferedWriter BufferedOutputStreamWriting to an array CharArrayWriter ByteArrayOutputStream
-
33
Writing to files FileWriter FileOutputStreamWriting to a pipe PipedWriter PipedOutputStreamWriting to a String StringWriter StringOutputStreamWriting primitive datatypes
None DataOutputStream
INPUT/OUTPUT EXCEPTIONSI/O Exception class Function
EOFException Signals that an end of the file or end of stream has
been reached unexpectedly during input
FileNotFoundException Informs that a file could not be found
InterruptedIOException Warns that an I/O operations has been interrupted
IOException Signals that an I/O exception of some sort has occurred
READING / WRITING CHARACTERS:Example for Character Stream classes
Characters.javaimport java.io.*;class Characters{
public static void main(String arg[]){//Declare and create input and output filesFile infile=new File (input.txt);File outfile=new File (output.txt);FileReader in=null;FileWriter out=null;try{
in=new FileReader(infile); //Opens input fileout=new FileWriter(outfile); //Opens ouput file
//Read and write characters till the endint ch;while((ch=in.read()) != -1) //Read until end of the file{
out.write(ch);}
} //End of try block
-
34
catch(IOException e){
System.out.println(e);System.out.println(-1);
} }}READING/WRITING BYTESExample for Byte Stream classesWriteBytes.javaimport java.io.*;class WriteBytes{
public static void main(String arg[]){//Declare and initialize a byte arraybyte cities [ ]= {'D','E','L','H','I','\n','C','H','E','N','N','A','I'};int ch;
FileOutputStream out=null; //Create an output filestreamtry{
out=new FileOutputStream("city.txt"); //connect outputstream to fileout.write(cities); //write data to the streamout.close();
}catch(IOException e){
System.out.println(e);}
FileInputStream in=null; //Create an output filestreamtry{
in=new FileInputStream("city.txt"); //connect inputstream to filewhile((ch=in.read()) != -1) //Read until end of the file{
System.out.print( (char) ch);}in.close();
}
catch(IOException e){
System.out.println(e);}
}}=====================================================================================
OUTPUT:
DELHI
CHENNAI