Upload
chandrasekhar-uchiha
View
229
Download
0
Embed Size (px)
Citation preview
8/3/2019 Java Unit IV
1/96
1
Unit- iv
Packages( Putting Classes Together )
8/3/2019 Java Unit IV
2/96
2
Introduction
The main feature of OOP is its ability to support thereuse of code:
Using the classes ( directly )
Extending the classes (via inheritance)
Extending interfaces
The features in basic form limited to reusing the classeswithin a program.
What if we want to reuse your classes in otherprograms without physically copying them ?
In Java, this is achieved by using packages, a concept
similar to class libraries in other languages.
8/3/2019 Java Unit IV
3/96
3
Creating your own packages
1. Pick a name for your package.
Ex : 1. mypackage
2. mypackage.util
java recommends lower case letters to the
package names.
8/3/2019 Java Unit IV
4/96
4
2. Choose a directory on your hard drive as
the root of your package classes library.
You need a place on your hard drive to store yourpackage classes.
I suggest you create a directory such asc:\javaclasses.
This folder becomes the root directory for yourpackages.
8/3/2019 Java Unit IV
5/96
5
3.Create subdirectories within the packageroot directory for your package name.
For example, for the package named mypackage.util,create a directory named mypackage in the
c:\javaclasses. Then, in the mypackage directory, create adirectory named util. Thus, the complete path to thedirectory that contains the classes for the mypackage.utilpackage is c:\javaclasses\mypackage\util.
8/3/2019 Java Unit IV
6/96
6
4.Save the files (classes ) you want to be in aparticular package in its corresponding packagedirectory and compile them.
For example, save the files that belongs to themypackage.util package in
c:\javaclasses\mypackage\util.
8/3/2019 Java Unit IV
7/96
7
5. Add the root directory for your package
to the ClassPath environment variable.
Do not disturb any directories already listed in theClassPath.
For example, suppose your ClassPath is already setto this: C:\Program Files\Java\jdk1.5.0_05\lib;
Then, you modify it to look like this:
C:\Program Files\Java\jdk1.5.0_05\lib;c:\javaclasses
8/3/2019 Java Unit IV
8/96
8
6. Add a package statement at the beginning
of source file.
The package statement creates a package with specifiedname.
All classes declared within that file belong to the specifiedpackage.
For example: package mypackage.util;
The package statement must be the first non-commentstatement in the file.
8/3/2019 Java Unit IV
9/96
9
Ex:
package mypackage.util;
public class sum{
public int sumInt(int a[]){
int sum=0;
for(int i=0;i
8/3/2019 Java Unit IV
10/96
10
Contd..import mypackage.util.*;
class pack_demo{
public static void main( String arg[]){
int x[]={1,2,3,4,5};
sum s=new sum();
System.out.println(s.sumInt(x));
}}
Note: This file can be compiled and executed form anyplace.
8/3/2019 Java Unit IV
11/96
11
In general, a Java source file can contain any
(or all) of the following four internal parts:
A single package statement (optional).
Any number of import statements (optional).
A single public class declaration (required).
Any number of classes private to thepackage (optional).
8/3/2019 Java Unit IV
12/96
12
Class access levels
A class has two access levels
default
public When a class is declared as public, it is accessible by
any other code.
If a class has default access, then it can only beaccessed by other code within the same package.
8/3/2019 Java Unit IV
13/96
13
Class members access levels
A Class member has four access levels
private
default protected
public
8/3/2019 Java Unit IV
14/96
14
Visibility areas are categorised into five
groups.
Same class .
Subclasses in the same package.
Non-subclasses in the same package.
Subclasses in different packages.
Non-subclasses in different packages.
8/3/2019 Java Unit IV
15/96
15
We can simplify access levels as follows:
Anything declared public can be accessedfrom anywhere.
Anything declared privatecannot be seen
outside of its class. default is visible to same class, subclasses
and non-subclasses in same package.
protectedis visible to same class,subclasses,
non-subclasses in the same package andsubclasses in different packages.
8/3/2019 Java Unit IV
16/96
16
To summarize
Class member access
8/3/2019 Java Unit IV
17/96
17
Accessing Classes from Packages
There are two ways of accessing theclasses stored in packages:
1. Using fully qualified class namejava.lang.Math.sqrt(x);
2.Import package and use class namedirectly.
import java.lang.Math;
Math.sqrt(x);
8/3/2019 Java Unit IV
18/96
18
Selected or all classes in packages can be
imported:
import package.ClassName;
import package.*;
8/3/2019 Java Unit IV
19/96
19
Understanding CLASSPATH
We should tell thejava run-time system where to lookfor packages that we have created.
There are three methods.
First, you can specify a path to package ( root path ) by settingthe CLASSPATHenvironmental variable.
Second, by default, the Java run-time system uses the current
working directory as its starting point. Thus, if your package isin the current directory, it will be found.
8/3/2019 Java Unit IV
20/96
20
Third, you can use the classpathoption withjavac andjava to specify the path to your
package classes. Example,
package mypackage.util;
Method-I : Add root dir to classpath envi variable thenexecute your program/class from any place.
Method-II : Execute your program/class from the rootdirectory ( current directory)
Method-III :>javac -classpath c:\rootdir path to ur java file
>java -classpath c:\rootdir;path to ur class classname
8/3/2019 Java Unit IV
21/96
21
anyplace :\> javac classpath package_rootpath
location_of_ur_java_file
anyplace :\>java -classpathpackagerootpath;ur_class_path ur_class_name
8/3/2019 Java Unit IV
22/96
22
Packages and Name Clashing
When packages are developed by differentorganizations, it is possible that multiple packageswill have classes with the same name, leading toname clashing.
class Teacher
package pack1;
class Student
class Student
package pack2;
class Courses
8/3/2019 Java Unit IV
23/96
23
We can import and use these packages like:
import pack1.*; import pack2.*;
Student student1=new Student(); //Generates compilation error
8/3/2019 Java Unit IV
24/96
24
Handling Name Clashing
In Java, name clashing is resolved by accessingclasses with their fully qualified name.
Example:
import pack1.*;
import pack2.*;
pack1.Student student1;
pack2.Student student2;Teacher teacher1;
Courses course1;
8/3/2019 Java Unit IV
25/96
25
Java Foundation Packages Java provides a large number of classes groped into
different packages based on their functionality.
The six Java foundation packages are: java.lang
Contains classes for math functions, Strings, threads, and exception java.util
Contains classes such as vectors, date, calendar etc.
java.io Classes for I/O
java.awt
Classes for implementing GUI windows, buttons, menus etc.
java.net Classes for networking
java.applet Classes for creating and implementing applets
8/3/2019 Java Unit IV
26/96
26
Interfaces
An interface,is a way of describing whatclassesshould do, without specifying howthey should do it.
Interfaces are syntactically similar to classes, but their
methods are declared without any body.
Any number of classes can implement an interface.
One class can implement any number of interfaces.
8/3/2019 Java Unit IV
27/96
27
Defining an Interface
The general form of an interface:
access_specifier interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type varname1 = value;
type varname2 = value;
...
...
}
8/3/2019 Java Unit IV
28/96
28
Here, access is either public or not used. Default indicates, the interface is only available to other members of the
package in which it is declared.
public indicates, the interface can be used by any other code.
Variables can be declared inside of an interface,
They are implicitly public, static and final.
They cannot be changed. They can be directly accessed by using interface name or class
name that implements interface.
They must be initialized with a constant value.
All methods declared in an interface are implicitly public.
Methods can not be declared as staticorfinal.
8/3/2019 Java Unit IV
29/96
29
Ex:-
// Define an integer stack interface.
interface IntStack
{
void push(int item); // store an item
int pop(); // retrieve an item
}
8/3/2019 Java Unit IV
30/96
30
Once an interfacehas been defined, one ormore classes can implement that interface.
The general form of a class that implementsaninterface.
access_specifier class classname [extends superclass][implements interface1 [,interface2...] ]
{
// class-body
}
8/3/2019 Java Unit IV
31/96
31
If a class implements more than one interface, the
interfaces are separated with a comma.
The type signature of the implementing method
must match exactly the type signature specified in
the interface definition.
When you implement an interface method, it must
be declared as public.
8/3/2019 Java Unit IV
32/96
32
Accessing Implementations ThroughInterface References
Any instance of any class that implements the interfacecan be referred by an interface variable.
When you call a method through an interface variable,
the correct version will be called based on the actualinstance of the class referred by the variable.
This is one of the keyfeatures of interfaces.
8/3/2019 Java Unit IV
33/96
33
The real power of interfaces:- For example, the stack can be of a fixed size or it can be
growable.
No matter how the stack is implemented, the interface to
the stack remains the same.
That is, the methods push( ) and pop( ) define the
interface to the stack independently of the details of the
implementation.
It is easier to addordelete the features to an application
with interfaces.
8/3/2019 Java Unit IV
34/96
34
The following program creates a class called FixedStack thatimplements a fixed-length version of an integer stack:
class FixedStack implements IntStack
{ int stack[];int tos;
FixedStack( int size)
{
stack = new int[size];
tos = -1;
}
8/3/2019 Java Unit IV
35/96
35
public void push( int item){
if(tos==stck.length-1)
System.out.println("Stack is full.");elsestck[++tos] = item;
}public intpop(){
if(tos==-1)
System.out.println("Stack is Underflow.");elsereturn stck[top--];
}}
8/3/2019 Java Unit IV
36/96
36
Another implementation of IntStack that creates a dynamic
stack by use of the same interface definition.
class DynStack implements IntStack{
int stack[];
int tos;
DynStack(int size){
stack = new int[size];
tos = -1;
}
8/3/2019 Java Unit IV
37/96
37
public void push( int item){
// if stack is full, allocate a larger stack
if(tos==stack.length-1)
{
int temp[] = new int[stack.length *2]; // double size
for(int i=0; i
8/3/2019 Java Unit IV
38/96
38
public int pop()
{if(tos==-1)
System.out.println("Stack is Underflow.");
elsereturn stck[top--];
}
}
8/3/2019 Java Unit IV
39/96
39
The following class uses both the FixedStack and
DynStack implementations.
class IFTest {public static void main(String args[]) {
IntStack mystack; // create an interface reference variable
DynStack ds = new DynStack(5);
FixedStack fs = new FixedStack(8);
mystack = ds; // load dynamic stack and push some numbers onto the stack
for(int i=0; i
8/3/2019 Java Unit IV
40/96
40
Variables in Interfaces
You can use interfaces to share constants among classes
by simply declaring an interface that contains variableswhich are initialized to the desired values.
Ex:-interface SharedConstants {
intNO = 0;intYES = 1;
intMAYBE = 2;
int LATER = 3;
int SOON = 4;
intNEVER = 5;
}
8/3/2019 Java Unit IV
41/96
41
Interfaces Can Be Extended
One interface can inherit another by use of thekeyword extends.
The syntax is similar to inheriting classes.
When a class implements an interface that
inherits another interface, it must provide
implementations for all methods defined within theinterface inheritance chain, otherwise that class
should be declared as abstract class.
8/3/2019 Java Unit IV
42/96
42
Ex:-interface A {
void meth1();
void meth2();
}interface B extends A {
void meth3();
}
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
8/3/2019 Java Unit IV
43/96
Java.util package
8/3/2019 Java Unit IV
44/96
1. The ArrayList Class
An array listis the most basic type of Javacollection.
Its similar to an array, but avoids many of
the most common problems of working witharrays.
Specifically:
8/3/2019 Java Unit IV
45/96
An array list automatically resizes itselfwhenever necessary.
If you create an array with 100 elements, then fill itup and need to add a 101stelement, youre out ofluck. The best you can do is create a new array with101 elements, copy the 100 elements from the oldarray to the new one, and then put the new data in
the 101st element. With an array list, theres never alimit to how many elements you can create.You cankeep adding elements as long as you want.
8/3/2019 Java Unit IV
46/96
An array list letsyou insertelements intothe middleofthe collection.
With an array, inserting elements is pretty hard todo. Suppose you have an array that can hold 100elements, but only the first50 have data.If youneed to insert a new element after the 25th item,
you must first make a copy of elements 26 through50 to make room for the new element. With an arraylist, you just say you want to insert the new elementafter the 25th item and the array list takes care ofshuffling things around.
8/3/2019 Java Unit IV
47/96
An array list letsyou delete items.
If you delete an item from an array, the deleted
element becomes null but the empty slot thatwas occupied by the item stays in the array.When you delete an item from an array list, anysubsequent items in the array are automatically
moved forward one position to fill in the spotthat was occupied by the deleted item.
8/3/2019 Java Unit IV
48/96
TheArrayList class actually uses anarray internallytostorethedata you
addtothe array list. When you add an item to the array list and the
underlying array is full, the ArrayList classautomatically creates a new array with a largercapacity and copies the existing items to thenew array before it adds the new item.
h i l
8/3/2019 Java Unit IV
49/96
49
The ArrayList ClassCreating ArrayList Object
ArrayList Constructors : ArrayList() -Creates an array list with an initial capacity
of 10 elements.
ArrayList( size ) Creates an array list with the specified initial capacity.
ArrayList al = new ArrayList();
Unlike an array, you dont have to specify a capacity for an array list. However,you can if you want. Heres a statement that creates an array list with an initialcapacity of 100:
ArrayList al= new ArrayList(100);
If you dont specify a capacity for the array list, the initial capacity is set to 10.Providing at least a rough estimate of how many elements each array list canhold when you create it is a good idea.
The capacity of an array list is not a fixed limit. The ArrayList classautomatically increases the lists capacity whenever necessary.
8/3/2019 Java Unit IV
50/96
If youre using Java 1.5, you can also specifythe type of elements the array list contains.
For example, this statement creates an arraylist that holds String objects:
ArrayList al = new ArrayList();
General formArrayList al=new ArrayList()
Here E specifies type of objects that the list willhold.For primitive data types we use followingnames:Integer, Float, Double, Character, Boolean, String
8/3/2019 Java Unit IV
51/96
Important methods of ArrayList
8/3/2019 Java Unit IV
52/96
8/3/2019 Java Unit IV
53/96
toString() Prints all the elements of ArrayList
8/3/2019 Java Unit IV
54/96
54
Ex
// Demonstrate ArrayList.import java.util.*;
class ArrayListDemo {public static void main(String args[]) {
ArrayList al = new ArrayList();System.out.println("Initial size of al: " +al.size());al.add("C");al.add("A");al.add("E");
al.add("B");al.add("D");al.add("F");al.add(1, "A2");System.out.println("Size of al after additions: " +al.size());System.out.println("Contents of al: " + al);al.remove("F");
al.remove(2);System.out.println("Size of al after deletions: " +al.size());System.out.println("Contents of al: " + al);
}}
8/3/2019 Java Unit IV
55/96
The LinkedList Class
The ArrayList class is based on an arrays. LinkedList class is based on pointers.
It is taken care by the LinkedList class
You dont have to do any pointer management
8/3/2019 Java Unit IV
56/96
Creating a LinkedList ObjectLinkedList class costructor
> LinkedList() - Creates an empty linked list.
LinkedList ls = new LinkedList();
If youre using Java 1.5, you can also specify the type of elements thearray list contains.
For example, this statement creates an array list that holds Stringobjects:
LinkedList al = new LinkedList();
General formLinkedList al=new LinkedList()
Here E specifies type of objects that the list will hold.For primitive datatypes we use following names: Integer, Float, Double, Character, Boolean, String
8/3/2019 Java Unit IV
57/96
Important methods of LinkedList
8/3/2019 Java Unit IV
58/96
8/3/2019 Java Unit IV
59/96
toString() Prints all the elements of LinkedList
The LinkedList Class
8/3/2019 Java Unit IV
60/96
60
The LinkedList Class
The LinkedListclass extends AbstractSequentialListand implements the List , Deque, and Queueinterfaces.
LinkedList Class is a generic class that has thisdeclaration:
class LinkedList
It provides a linked-list data structure.It has the twoconstructors, shown here:
LinkedList( )LinkedList(Collection c)
The first constructor builds an empty linked list. Thesecond constructor builds a linked
list that is initialized with the elements of the collection
8/3/2019 Java Unit IV
61/96
61
Ex// Demonstrate LinkedList.
import java.util.*;class LinkedListDemo {public static void main(String args[]) {
LinkedList ll = new LinkedList();
ll.add("F");ll.add("B");ll.add("D");ll.add("E");ll.add("C");ll.addLast("Z");
ll.addFirst("A");ll.add(1, "A2");
8/3/2019 Java Unit IV
62/96
62
System.out.println("Original contents of ll: " + ll);// remove elements from the linked listll.remove("F");ll.remove(2);System.out.println("Contents of ll after deletion: + ll);// remove first and last elementsll.removeFirst();
ll.removeLast();System.out.println("ll after deleting first and last: "+ ll);// get and set a valueString val = ll.get(2);ll.set(2, val + " Changed");
System.out.println("ll after change: " + ll);}}
8/3/2019 Java Unit IV
63/96
63
java.util Part2: More
Utility Classes
StringTokenizer
8/3/2019 Java Unit IV
64/96
64
StringTokenizer
TheString
Tokenizer constructors are shown here:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, booleandelimAsToken)
In the first version, the default delimiters are used.
The default set of delimiters consists of the whitespacecharacters: pace, tab, newline.
In the second and third versions, delimiters is a string
that specifies the delimiters. In the third version, if delimAsToken is true, then the
delimiters are also returned as tokens when the string isparsed.
Methods Defined by StringTokenizer
8/3/2019 Java Unit IV
65/96
65
Methods Defined by StringTokenizer
Method Description
int countTokens( ) Returns number of tokens left to be parsed.
booleanhasMoreTokens( )
Returns trueif one or more tokens remain in
the string and returns falseif there are none.
Object nextElement( ) Returns the next token as an Object.
Date
8/3/2019 Java Unit IV
66/96
66
Date
The Dateclass encapsulates the current date and time.
Datesupports the following constructors:Date( )
Date(long millisec) The first constructor initializes the object with the
current date and time.
The second constructor accepts one argument that
equals the number of milliseconds that have elapsedsince midnight, January 1, 1970.
8/3/2019 Java Unit IV
67/96
67
Methods defined by Date class
Method Descriptionboolean after(Date date) Returns trueif the invoking Dateobject contains a
date that is later than the one specified by date.Otherwise, it returns false.
boolean before(Date
date)
Returns trueif the invoking Dateobject contains a
date that is earlier than the one specified by date.Otherwise, it returns false.
Object clone( ) Duplicates the invoking Dateobject.
int compareTo(Date date) Compares the value of the invoking object withthat of date. Returns 0 if the values are equal.Returns a negative value if the invoking object isearlier than date. Returns a positive value if theinvoking object is later than date. (Added by Java2)
8/3/2019 Java Unit IV
68/96
68
Contd..
Method Description
boolean equals(Objectdate)
Returns trueif the invoking Dateobject containsthe same time and date as the one specified bydate.Otherwise, it returns false.
long getTime( ) Returns the number of milliseconds that haveelapsed since January 1, 1970.
void setTime(long time) Sets the time and date as specified by time, whichrepresents an elapsed time in milliseconds frommidnight, January 1, 1970.
String toString( ) Converts the invoking Dateobject into a string andreturns the result.
Calendar
8/3/2019 Java Unit IV
69/96
69
Calendar
The abstractCalendar class provides a set of methodsthat allows you to convert a time in milliseconds to anumber of useful components.
Ex:- year month day hour minute second.
Subclasses ofCalendar will provide the specificfunctionality to interpret time information according totheir own rules.
An example of such a subclass is GregorianCalendar.
8/3/2019 Java Unit IV
70/96
70
Calendar defines the following int constants, which areused when you get or set components of the calendar:
AM
PM FRIDAYHOUR SATURDAY
APRIL HOUR_OF_DAY SECOND
AUGUST JANUARY SEPTEMBER
DATE JULY SUNDAYDAY_OF_MONTH JUNE THURSDAY
DAY_OF_WEEK MARCH TUESDAY
DAY_OF_WEEK_IN_MONTH MAY
DAY_OF_YEAR MILLISECOND WEDNESDAY
DECEMBER MINUTE WEEK_OF_MONTH
MONDAY WEEK_OF_YEAR
MONTH YEAR OCTOBER
FEBRUARY NOVEMBER
8/3/2019 Java Unit IV
71/96
71
Some commonly used methods defined by Calendar
Method Description
abstract void add(int which,int val)
Adds val to the time or date component specifiedby which. To subtract, add a negative value. Whichmust be one of the fields defined by Calendar, suchas Calendar.HOUR.
boolean after(ObjectcalendarObj) Returns trueif the invokingC
alend
ar objectcontains a date that is later than the one specifiedby calendarObj.Otherwise, it returns false.
boolean before(ObjectcalendarObj)
Returns trueif the invoking Calendar objectcontains a date that is earlier than the one specified
by calendarObj.Otherwise, it returns false.
final void clear( ) Zeros all time components in the invoking object.
8/3/2019 Java Unit IV
72/96
72
Contd..final void clear(int which) Zeros the time component specified by which in the invoking
object.
static Calendar getInstance( ) Returns a Calendar object for the default locale and timezone.
void set(int which, int val) Sets the date or time component specified by which to thevalue specified by val in the invoking object.
which must be one of the fields defined by Calendar,
such as Calendar.HOUR.
final void set(int year, intmonth,int dayOfMonth)
Sets various date and time components of the invokingobject.
final void set(int year, intmonth, int dayOfMonth, int
hours, int minutes)
Sets various date and time components of the invokingobject
final void set(int year, intmonth, int dayOfMonth, inthours, int minutes, intseconds)
Sets various date and time components of the invokingobject
8/3/2019 Java Unit IV
73/96
73
GregorianCalendar
GregorianCalendar is a concrete implementation of aCalendar that provides the normal Gregorian calendarwith which you are familiar.
The getInstance( ) method of
Calen
dar returns aGregorianCalendar initialized with the current date
and time.
There are also several constructors forGregorianCalendar class.
The default, GregorianCalendar( ), initializes theobject with the current local date and time.
8/3/2019 Java Unit IV
74/96
74
Contd..
Three more constructors GregorianCalendar(int year, int month, int dayOfMonth) GregorianCalendar(int year, int month, int dayOfMonth, int
hours,int minutes)
GregorianCalendar(int year, int month, int dayOfMonth, inthours,int minutes, int seconds)
GregorianCalendar provides an implementation of allthe abstract methods in Calendar.
It also provides some additional methods.
Ex:-
boolean isLeapYear(int year)
8/3/2019 Java Unit IV
75/96
75
Ex:-
// Demonstrate GregorianCalendar
import java.util.*;
class GregorianCalendarDemo {
public static void main(String args[]) {
String months[] = {
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
int year;
// Create a Gregorian calendar initialized
// with the current local date and time in the
GregorianCalendar gcalendar = new GregorianCalendar();
C td
8/3/2019 Java Unit IV
76/96
76
Contd..
// Display current time and date information.
System.out.print("Date: ");System.out.print(months[gcalendar.get(Calendar.MONTH)]);System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");System.out.println(year = gcalendar.get(Calendar.YEAR));System.out.print("Time: ");System.out.print(gcalendar.get(Calendar.HOUR) + ":");
System.out
.print(gcalendar
.get(Calendar
.MINUTE) + ":");System.out.println(gcalendar.get(Calendar.SECOND));
// Test if the current year is a leap yearif(gcalendar.isLeapYear(year)) {System.out.println("The current year is a leap year");}else {System.out.println("The current year is not a leap year");}}}
java io package
8/3/2019 Java Unit IV
77/96
77
java.io package.
java.io package.
Some basic points aboutI/O:
A stream is a linear, sequential flow of bytes of input oroutput data.
Streams are written to the file system to create files.
Streams can also be transferred over the Internet.
Basic input and output classes
8/3/2019 Java Unit IV
78/96
78
Basic input and output classes
The java.io package contains a fairly large number of
classes that deal with Java input and output.
Most of the classes consist of: Byte streams that are subclasses ofInputStream or
OutputStream
Character streams that are subclasses of Reader and Writer InputStream reads 8-bit bytes, while OutputStream
writes 8-bit bytes.
Suitable for sound and image files.
The Reader and Writer classes read and write 16-bitUnicode characters.
In Unicode, two bytes make a character.
h b f diff i
8/3/2019 Java Unit IV
79/96
79
There are a number of different questions toconsider when dealing java.io package:
What is your format: text or binary?Are you dealing with objects or non-objects?
What are your sources and sinks for data?
Do you need to use filtering?
Sources and sinks for data
What is the source of your data?
What will be consuming your output data, that is,acting as a sink?
8/3/2019 Java Unit IV
80/96
80
You can input or output your data in a numberof ways:
Sockets ( network ) files ( disk )
strings, and arrays of characters ( memory )
Any of these can be a source for an InputStream or
Reader or a sink for an OutputStream or Writer.
Filtering Buffering
Compression
Encryption Buffering is one filtering method.Instead of going back to the
operating system for each byte, you can use a buffer to improve theperformane.
8/3/2019 Java Unit IV
81/96
81
Subclasses ofInputStream
InputStream
ByteArrayInputStream
FileInputStream
FilterInputStream
PipedInputStream
SequenceInputStream
DataInputStream
BufferedInputStream
LineNumberInputStream
PushbackInputStream
Object
The Byte Streams
8/3/2019 Java Unit IV
82/96
82
The Byte Streams
InputStream InputStream is an abstract class that defines
Javas model of streaming byte input.
All of the methods in this class will throw anIOException on error conditions.
The following are the methods in InputStream.
8/3/2019 Java Unit IV
83/96
83
8/3/2019 Java Unit IV
84/96
84
OutputStream OutputStream is an abstract class that defines Javas model
of streaming byte output. All of the methods in this class return a voidvalue.
FileInputStream
8/3/2019 Java Unit IV
85/96
85
FileInputStream
The FileInputStream class creates an
InputStream that you can use to read bytesfrom a file.
Its two most common constructors are shownhere:
FileInputStream(String filepath)
FileInputStream(File fileObj)
FileOutputStream
8/3/2019 Java Unit IV
86/96
86
FileOutputStream
FileOutputStream creates an OutputStream thatyou can use to write bytes to a file.
Its most commonly used constructors are shown here: FileOutputStream(String filePath)
FileOutputStream(File fileObj) FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
ByteArrayInputStream
8/3/2019 Java Unit IV
87/96
87
ByteArrayInputStream
ByteArrayInputStream is an implementationof an input stream that uses a byte array as thesource.
This class has two constructors, each of whichrequires a byte array to provide the datasource: ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)
// Demonstrate ByteArrayInputStream
8/3/2019 Java Unit IV
88/96
88
// Demonstrate ByteArrayInputStream.
import java.io.*;
class ByteArrayInputStreamDemo {
public static void main(String args[]) throws IOException {String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3);
}
}
The input1object contains the entire lowercase alphabet, whileinput2contains only the first three letters.
A ByteArrayInputStream implements both mark( )
and reset( ). However, ifmark( ) has not been called, then reset( )
sets the stream pointer to the start of the stream
ByteArrayOutputStream
8/3/2019 Java Unit IV
89/96
89
ByteArrayOutputStream ByteArrayOutputStream is an implementation of an
output stream that uses a byte array as the destination.
ByteArrayOutputStream has two constructors,shown here: ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)
In the first form, a buffer of32 bytes is created. In the second, a buffer is created with a size equal to that
specified by numBytes.
The buffer is held in the protected buffield ofByteArrayOutputStream.
The buffer size will be increased automatically, if needed.
Filtered Byte Streams
8/3/2019 Java Unit IV
90/96
90
iltered yte Streams
Filter input streams read data from a preexisting input
stream such as a FileInputStream
These streams have an opportunity to work with orchange the data before it is delivered to the clientprogram.
Filter output streams write data to a preexisting outputstream such as a FileOutputStream and have anopportunity to work with or change the data before it is
written onto the underlying stream.
8/3/2019 Java Unit IV
91/96
91
The filtered byte streams are FilterInputStream andFilterOutputStream.
FilterOutputStream(OutputStream os)
FilterInputStream(InputStream is)
The methods provided in these classes are identical tothose in InputStream and OutputStream.
BufferedInputStream
8/3/2019 Java Unit IV
92/96
92
p
Javas BufferedInputStream class allows you to
wrap any InputStream into a buffered stream andachieves performance improvement.
BufferedInputStream has two constructors: BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize) The first form creates a buffered stream using a default
buffer size (2048 bytes).
In the second, the size of the buffer is passed inbufSize.
Because the buffer is available,skipping, marking, andresetting of the stream becomes possible.
8/3/2019 Java Unit IV
93/96
93
When the first call to read() is made, the BufferedInputStreamreads in 2048 bytes (the default size of the buffer) and simplyreturns 1 byte at a time from the buffer for subsequent reads.
There are certainly hardware and operating system caches
involved as well, but it is always going to be faster to satisfy aread request from a memory location within the program than it isto make a system call to the operating system.
It would also be more efficient to read more than one byte at atime from the stream, especially if it is unbuffered, but as we willsee in the next section, some data types within a stream are only
made up of a few bytes, so the value ofBufferedInputStream still
exists.
8/3/2019 Java Unit IV
94/96
94
Buffered Byte Streams
8/3/2019 Java Unit IV
95/96
95
y
8/3/2019 Java Unit IV
96/96
In computing, the carriage return (CR)is one of the control characters inASCIIcode or EBCDIC that commands a printer
or other sort of display to move theposition of the cursor to the first positionon the same line.It is mostly used alongwith line feed, a move to the next line,
while carriage return precedes line feedto indicate new line.