• A class to display a simple message:
class MyProgram
{
public static void main(String[] args)
{
System.out.println(“First Java program.");
}
}
Simple Java Program
• Real world objects are things that have:
1) state
2) behavior
Example: your dog:
• state – name, color, breed, sits?, barks?, wages tail?,
runs?
• behavior – sitting, barking, waging tail, running
• A software object is a bundle of variables (state) and
methods (operations).
What is an Object?
• A class is a blueprint that defines the variables
and methods common to all objects of a
certain kind.
• Example: ‘your dog’ is a object of the class
Dog.
• An object holds values for the variables
defines in the class.
• An object is called an instance of the Class
What is a Class?
• A variable is declared to refer to the objects of
type/class String:
String s;
• The value of s is null; it does not yet refer to any
object.
• A new String object is created in memory with initial
“abc” value:
• String s = new String(“abc”);
• Now s contains the address of this new object.
Object Creation
• A program accumulates memory through its
execution.
• Two mechanism to free memory that is no longer
need by the program:
1) manual – done in C/C++
2) automatic – done in Java
• In Java, when an object is no longer accessible
through any variable, it is eventually removed
from the memory by the garbage collector.
• Garbage collector is parts of the Java Run-Time
Environment.
Object Destruction
• A basis for the Java language.
• Each concept we wish to describe in Java must
be included inside a class.
• A class defines a new data type, whose values
are objects:
• A class is a template for objects
• An object is an instance of a class
Class
 A class contains a name, several variable declarations (instance
variables) and several method declarations. All are called
members of the class.
 General form of a class:
class classname {
type instance-variable-1;
…
type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }
…
type method-name-m(parameter-list) { … }
}
Class Definition
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
} }
Example: Class Usage
// This program declares two Box objects.
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
• A constructor initializes the instance variables of an object.
• It is called immediately after the object is created but before
the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default
return type of a class
• constructor is the same class
• When the class has no constructor, the default constructor
automatically initializes all its instance variables with zero.
Constructor
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}
Example: Constructor
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
Parameterized Constructor
 General form of a method definition:
type name(parameter-list) {
… return value;
…
}
 Components:
1) type - type of values returned by the method. If a method
does not return any value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists
separated by commas
4) return value indicates what value is returned by the
method.
Methods
• Classes declare methods to hide their internal data
structures, as well as for their own internal use: Within a
class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
Example: Method
• Parameters increase generality and applicability of a
method:
• 1) method without parameters
int square() { return 10*10; }
• 2) method with parameters
int square(int i) { return i*i; }
• Parameter: a variable receiving value at the time the
method is invoked.
• Argument: a value passed to the method when it is
invoked.
Parameterized Method
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables
and methods.
• Encapsulation, safely sealing data within the capsule
of the class Prevents programmers from relying on
details of class implementation, so you can update
without worry
• Helps in protecting against accidental or wrong
usage.
• Keeps code elegant and clean (easier to maintain)
Access Modifiers: Public, Private,
Protected
• Public: keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.
• Default(No visibility modifier is specified): it
behaves like public in its package and private
in other packages.
• Default Public keyword applied to a class,
makes it available/visible everywhere.
Applied to a method or variable, completely
visible.
• Private fields or methods for a class only
visible within that class. Private members are
not visible within subclasses, and are not
inherited.
• Protected members of a class are visible
within the class, subclasses and also within all
classes that are in the same package as that
class.
Visibility
public class Circle {
private double x,y,r;
// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
Keyword this
• Can be used by any object to refer to itself
in any class method
• Typically used to
– Avoid variable name collisions
– Pass the receiver as an argument
– Chain constructors
• Keyword this allows a method to refer to the object
that invoked it.
• It can be used inside any method to refer to the
current object:
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Keyword this
• Garbage collection is a mechanism to remove objects from
memory when they are no longer needed.
• Garbage collection is carried out by the garbage collector:
• 1) The garbage collector keeps track of how many references
an object has.
• 2) It removes an object from memory when it has no longer
any references.
• 3) Thereafter, the memory occupied by the object can be
allocated again.
• 4) The garbage collector invokes the finalize method.
Garbage Collection
• A constructor helps to initialize an object just after it
has been created.
• In contrast, the finalize method is invoked just before
the object is destroyed:
• 1) implemented inside a class as:
protected void finalize() { … }
• 2) implemented when the usual way of removing
objects from memory is insufficient, and some
special actions has to be carried out
finalize() Method
• It is legal for a class to have two or more methods
with the same name.
• However, Java has to be able to uniquely associate
the invocation of a method with its definition
relying on the number and types of arguments.
• Therefore the same-named methods must be
distinguished:
• 1) by the number of arguments, or
• 2) by the types of arguments
• Overloading and inheritance are two ways to
implement polymorphism.
Method Overloading
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a); return a*a;
}
}
Example: Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}
Constructor Overloading
• Two types of variables:
1) simple types
2) class types
• Two corresponding ways of how the arguments are
passed to methods:
• 1) by value a method receives a cope of the original
value; parameters of simple types
• 2) by reference a method receives the memory
address of the original value, not the value itself;
parameters of class types
Parameter Passing
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.print("a and b before call: “);
System.out.println(a + " " + b);
ob.meth(a, b);
System.out.print("a and b after call: ");
System.out.println(a + " " + b);
}
}
Call by value
• As the parameter hold the same address as the argument, changes to the
object inside the method do affect the object used by the argument:
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.print("ob.a and ob.b before call: “);
System.out.println(ob.a + " " + ob.b);
ob.meth(ob);
System.out.print("ob.a and ob.b after call: ");
System.out.println(ob.a + " " + ob.b);
}
}
Call by refference
• A recursive method is a method that calls itself:
1) all method parameters and local variables are
allocated on the stack
2) arguments are prepared in the corresponding
parameter positions
3) the method code is executed for the new
arguments
4) upon return, all parameters and variables are
removed from the stack
5) the execution continues immediately after the
invocation point
Recursion
class Factorial {
int fact(int n) {
if (n==1) return 1;
return fact(n-1) * n;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.print("Factorial of 5 is ");
System.out.println(f.fact(5));
} }
Example: Recursion
• String is probably the most commonly used class in
Java's class library. The obvious reason for this is that
strings are a very important part of programming.
• The first thing to understand about strings is that every
string you create is actually an object of type String.
Even string constants are actually String objects.
• For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String constant
String Handling
• Java defines one operator for String objects: +.
• It is used to concatenate two strings. For example,
this statement
• String myString = "I" + " like " + "Java.";
results in myString containing
"I like Java."
• The String class contains several methods that you
can use. Here are a few. You can
• test two strings for equality by using
equals( ). You can obtain the length of a string by
calling the length( ) method. You can obtain the
character at a specified index within a string by
calling charAt( ). The general forms of these three
methods are shown here:
• // Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +
strOb1.length());
System.out.println ("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
} }
This program generates the following output:
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3
Argument Passing
call-by-value
call-by-value copies the value of an argument into the formal parameter of the
subroutine.
Changes made to the parameter of the subroutine have no effect on the argument.
call-by-reference
call-by-reference , a reference to an argument (not the value of the argument) is passed
to the parameter.
Changes made to the parameter will affect the argument used to call the subroutine. As
you will see, Java uses both approaches, depending upon what is passed.
Encapsulation provides another important attribute: access control.
Encapsulation - control what parts of a program can access the members of a
class.
Prevent misuse.
Java’s access specifiers are public, private, and protected
Java also defines a default access level. protected applies only when
inheritance is involved.
When a member of a class is modified by the public specifier, then that
member can be accessed by any other code.
When a member of a class is specified as private, then that member can only
be accessed by other members of its class.
Static - When a member is declared static, it can be accessed before any objects of
its class are created, and without reference to any object.
Both methods and variables to be static.
The most common example of a static member is main( ).
Instance variables declared as static are, essentially, global variables. When objects
of its class are declared, no copy of a static variable is made. Instead, all instances
of the class share the same static variable.
Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
Call a static method from outside its class,
general form: classname.method( )
The final keyword in java is used to restrict the user.
Final can be:
variable
method
Class
Final Variable
Variable as final, you cannot change the value of final variable(It
will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Java final method
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Final method is inherited but you cannot override it
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Java final class
If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
}
}
String
String is a sequence of characters.
Other languages that implement strings as character arrays
Java implements strings as objects of type String.
Once a String object has been created, you cannot change the
characters that comprise that string
Java provides two options: StringBuffer and StringBuilder.
Both hold strings that can be modified after they are created.
The strings within objects of type String are unchangeable means that the contents
of the String instance cannot be changed after it has been created.
A variable declared as a String reference can be changed to point at some other
String object at any time.
The String Constructors
To create an empty String
String s = new String();
you will want to create strings that have initial values
String(char chars[ ])
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
You can specify a subrange of a character array as an initializer using the
following constructor:
String(char chars[ ], int startIndex, int numChars)
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
You can construct a String object that contains the same character sequence as
another String object using this constructor:
String(String strObj)
String Constructors Added by J2SE 5
String(int codePoints[ ], int startIndex, int numChars)
codePoints is an array that contains Unicode code points
String(StringBuilder strBuildObj)
String Length
int length( )
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Special String Operations
The automatic creation of new String instances from string literals
 Concatenation of multiple String objects by use of the + operator,
The conversion of other data types to a string representation.
There are explicit methods available to perform all of these funtions, but Java does
them automatically as a convenience for the programmer
String Literals
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc";
you can call methods directly on a quoted string as if it were an object reference,
as the following statement shows.
System.out.println("abc".length());
String Concatenation
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
String Concatenation with Other Data Types
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
String s = "four: " + 2 + 2;
System.out.println(s);
This fragment displays
four: 22
rather than the
four: 4
To complete the integer addition first, you must use parentheses, like this:
String s = "four: " + (2 + 2);
Now s contains the string “four: 4”.
String Conversion and toString( )
// Override toString() for Box class.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
public String toString() {
return "Dimensions are " + width + " by " +
depth + " by " + height + ".";
} }
class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
} }
Naming conventions
• Java naming convention is a rule to follow as
you decide what to name your identifiers such
as class, package, variable, constant, method
etc.
• But, it is not forced to follow. So, it is known as
convention not rule.
• All the classes, interfaces, packages, methods
and fields of java programming language are
given according to java naming convention.
Advantage of naming conventions in
java
• By using standard Java naming conventions,
you make your code easier to read for yourself
and for other programmers.
• Readability of Java program is very important.
It indicates that less time is spent to figure out
what the code does.
convention
Name Convention
class name should start with uppercase letter and be
a noun e.g. String, Color, Button, System,
Thread etc.
interface name should start with uppercase letter and be
an adjective e.g. Runnable, Remote,
ActionListener etc.
method name should start with lowercase letter and be
a verb e.g. actionPerformed(), main(),
print(), println() etc.
variable name should start with lowercase letter e.g.
firstName, orderNumber etc.
package name should be in lowercase letter e.g. java,
lang, sql, util etc.
constants name should be in uppercase letter. e.g. RED,
YELLOW, MAX_PRIORITY etc.
Java bean
A Java Bean is a java class that should follow following conventions:
It should have a no-arg constructor.
It should be Serializable.
It should provide methods to set and get the values of the properties, known as getter
and setter methods.
Why use Java Bean?
• According to Java white paper, it is a reusable
software component.
• A bean encapsulates many objects into one
object, so we can access this object from
multiple places.
• Moreover, it provides the easy maintenance.
Definitions
• A reusable software component that can be
manipulated visually in a ‘builder tool’. (from
JavaBean Specification)
• The JavaBeans API provides a framework for
defining reusable, embeddable, modular
software components.
Simple example of java bean class
//employee.java
Package mypack;
Public class employee
implementsjava.io.serializiable
{
private int id;
private string name;
public employee()
{ }
public void setId(int id)
{
this.id=id;
}
public int getId()
{
Return id;
}
Public void setName(String name)
{
This.name=name;
}
Public string getName()
{
Return name;
} }
How to access the java bean class?
Package mypack;
Public class test
{
Public static void main(string args[])
{
Employee e=new employee();
e.setName(“Arjun”);
System.out.println(e.getName());
e.setId(10112);
System.out.println(e.getId());
}
}
Advantages of Java Beans
• The following list enumerates some of the benefits that Java Bean
technology provides for a component developer:
• • A Bean obtains all the benefits of Java’s “write-once, run-
anywhere” paradigm.
• The properties, events, and methods of a Bean that are exposed to
another application can be controlled.
• • Auxiliary software can be provided to help configure a Bean. This
software is only needed when the design-time parameters for that
component are being set. It does not need to be included in the
run-time environment.
• • The state of a Bean can be saved in persistent storage and
restored at a later time.
• • A Bean may register to receive events from other objects and can
generate events that are sent to other objects.
Introspection
• At the core of Java Beans is introspection. This
is the process of analyzing a Bean to
determine its capabilities.
• This is an essential feature of the Java Beans
API because it allows another application,
such as a design tool, to obtain information
about a component. Without introspection,
the Java Beans technology could not operate.
Design Patterns for Properties
• A property is a subset of a Bean’s state. The
values assigned to the properties determine
the behavior and appearance of that
component. A property is set through a setter
method.
• property is obtained by a getter method.
There are two types of properties: simple and
indexed
Simple property
• A simple property has a single value. It can be
identified by the following design patterns,
• where N is the name of the property and T is its
type:
• public T getN( )
• public void setN(T arg)
• A read/write property has both of these methods
to access its values.
• A read-only property has only a get method. A
write-only property has only a set method.
Simple property
• private double depth, height, width;
• public double getDepth( ) {
• return depth;
• }
• public void setDepth(double d) {
• depth = d;
• }
• public double getHeight( ) {
• return height;
• }
• public void setHeight(double h) {
• height = h;
• }
• public double getWidth( ) {
• return width;
• }
• public void setWidth(double w) {
• width = w;
• }
• An indexed property consists of multiple values. It
can be identified by the following design
• patterns, where N is the name of the property
and T is its type:
• public T getN(int index);
• public void setN(int index, T value);
• public T[ ] getN( );
• public void setN(T values[ ]);
Indexed property
• Here is an indexed property called data along with its getter and setter methods:
• private double data[ ];
• public double getData(int index) {
• return data[index];
• }
• public void setData(int index, double value) {
• data[index] = value;
• }
• public double[ ] getData( ) {
• return data;
• }
• public void setData(double[ ] values) {
• data = new double[values.length];
• System.arraycopy(values, 0, data, 0, values.length);
• }
Bound and Constrained Properties
• A Bean that has a bound property generates an
event when the property is changed. Theevent is
of type PropertyChangeEvent and is sent to
objects that previously registered an interest in
receiving such notifications. A class that handles
this event must implement the
• PropertyChangeListener interface.
• A Bean that has a constrained property generates
an event when an attempt is made tochange its
value. It also generates an event of type
PropertyChangeEvent
beaninfo
• The BeanInfo interface enables you to explicitly control what
• information is available.
• The BeanInfo interface defines several methods, including these:
PropertyDescriptor[ ] getPropertyDescriptors( )
EventSetDescriptor[ ] getEventSetDescriptors( )
MethodDescriptor[ ] getMethodDescriptors( )
They return arrays of objects that provide information about the properties, events, and
methods of a Bean. The classes PropertyDescriptor, EventSetDescriptor, and MethodDescriptor
are defined within the java.beans package, and they describe the indicated elements. By
implementing these methods, a developer can designate exactly what is presented to a user,
bypassing introspection based on design patterns.
When creating a class that implements BeanInfo, you must call that class bnameBeanInfo,
where bname is the name of the Bean. For example, if the Bean is called MyBean, then the
information class must be called MyBeanBeanInfo.
Persistence
• Persistence is the ability to save the current state of a
Bean, including the values of a Bean’s properties and
instance variables, to nonvolatile storage and to
retrieve them at a later time.
• The object serialization capabilities provided by the
Java class libraries are used to provide persistence for
Beans.
• The easiest way to serialize a Bean is to have it
implement the java.io.Serializable
• interface, which is simply a marker interface.
Implementing java.io.Serializable makes
• serialization automatic.
Customizers
• A Bean developer can provide a customizer
that helps another developer configure the
Bean.
• A customizer can provide a step-by-step guide
through the process that must be followed to
use the component in a specific context.
Intro to JavaBeans
• What are JavaBeans?
– Software components written in Java
– Connect and Configure Components
– Builder Tools allow connection and
configuration of Beans
– Begins ‘Age of Component Developer’
– Bringing Engineering methods to Software
Engineering (e.g. electronics…)
The JavaBeans API
• Features implemented as extensions to
standard Java Class Library
• Main Component Services
– GUI merging
– Persistence
– Event Handling
– Introspection
– Application Builder Support
User Interface Merging
• Containers usually have Menus and/or
toolbars
• Allows components to add features to the
menus and/or toolbars
• Define mechanism for interface layout
between components and containers
Persistence
• Components can be stored and retrieved
• Default – inherit serialization
• Can define more complex solutions based on
needs of the components
Event Handling
• Defines how components interact
• Java AWT event model serves as basis for the
event handling API’s
• Provides a consistent way for components to
interact with each other
Introspection
• Defines techniques so components can
expose internal structure at design time
• Allows development tools to query a
component to determine member
variables, methods, and interfaces
• Standard naming patterns used
• Based on java.lang.reflect
Application Builder Support
• Provides support for manipulating and editing
components at design time
• Used by tools to provide layout and
customizing during design
• Should be separate from component
• Not needed at run time
Bean Requirements
• Introspection
– Exports: properties, methods, events
• Properties
– Subset of components internal state
• Methods
– Invoked to execute component code
• Events (If any needed)
– Notification of a change in state
– User activities (typing, mouse actions, …)
Bean Requirements
• Customization
– Developer can change appearance
• Persistence
– Save current state so it can be reloaded
Other properties
• Indexed properties
– Array value with get and set elements
• Bound properties
– Triggers event when value changed
• Constrained properties
– Triggers event when value changes and allows
listeners to ‘veto’ the change
BeanInfo class
• Provides more information using
FeatureDescripter objects
• Subclasses:
– BeanDescripter, PropertyDescripter,
IndexedPropertyDescripter, EventSetDescripter,
MethodDescripter, ParameterDescripter
BeanInfo class
• ICON to represent Bean
• Customizer Class (wizard for set up)
• Property Editor references
• List of properties with descriptions
• List of methods with descriptions
• Method to reset properties to defaults
The beanbox
• Primary task is setting property values
• Property editors for common types
– Set Font
– Set background/foreground colors
– Set numeric values
– Set string values
I/O basics
• The io package supports Java’s basic I/O
(input/out
• Java does provide strong, flexible support for
I/O as it relates to files and networks. Java’s
I/O system is cohesive and consistent.
• In fact, once you understand its fundamentals,
the rest of the I/O system is easy to
masterput) system, including file I/O.
STREAMS
• A stream is an abstraction that either produces or
consumes information.
• A stream is linked to a physical device by the Java I/O
system.
This means that an input stream can abstract many
different kinds of input: from a disk file, a keyboard, or a
network socket
• Likewise, an output stream may refer to the console, a
disk file, or a network connection.. Java implements
streams within class hierarchies defined in the
• java.io package.
BYTE AND CHARACTER STREAMS
• Java defines two types of streams: byte and
character.
• Byte streams provide a convenient means for
handling input and output of bytes. Byte
streams are used, for example, when reading
or writing binary data.
• Character streams provide a convenient
means for handling input and output of
characters.
The Byte Stream Classes
• The Byte Stream Classes
• Byte streams are defined by using two class
hierarchies. At the top are two abstract
classes:
• InputStream and OutputStream. Each of
these abstract classes has several concrete
subclasses that handle the differences among
various devices, such as disk files, network
• connections, and even memory buffers.
BYTE STREAM CLASSES IN java.io
• Stream Class Meaning
• BufferedInputStream---------- Buffered input stream
• BufferedOutputStream----------- Buffered output stream
• ByteArrayInputStream -------------Input stream that reads from a byte array
• ByteArrayOutputStream----------- Output stream that writes to a byte array
• DataInputStream --------------An input stream that contains methods for reading the Java standard data types
• DataOutputStream------------------ An output stream that contains methods for writing the Java standard data types
• FileInputStream-------------------- Input stream that reads from a file
• FileOutputStream ------------------------Output stream that writes to a file
• FilterInputStream------------------------- Implements InputStream
• FilterOutputStream ---------------------Implements OutputStream
• InputStream ---------------------Abstract class that describes stream input
• ObjectInputStream ---------------------Input stream for objects
• ObjectOutputStream-------------------- Output stream for objects
• OutputStream -----------------------Abstract class that describes stream output
• PipedInputStream------------------------------ Input pipe
• PipedOutputStream---------------------- Output pipe
• PrintStream -------------------Output stream that contains print( ) and println( )
• PushbackInputStream ------------Input stream that supports one-byte “unget,” which returns a byte to the input
stream
• SequenceInputStream----------------------- Input stream that is a combination of two or more input streams that will
be read sequentially, one after the other
Character stream classes
• The Character Stream Classes
• Character streams are defined by using two
class hierarchies. At the top are two abstract
• classes: Reader and Writer. These abstract
classes handle Unicode character streams.
Java has several concrete subclasses of each of
these
Character stream classes
• Stream Class Meaning
• BufferedReader --------------Buffered input character stream
• BufferedWriter----------------- Buffered output character stream
• CharArrayReader---------------- Input stream that reads from a character array
• CharArrayWriter------------------ Output stream that writes to a character array
• FileReader-------------------------- Input stream that reads from a file
• FileWriter ---------------------------Output stream that writes to a file
• FilterReader------------------------- Filtered reader
• FilterWriter--------------------------- Filtered writer
• InputStreamReader------------------ Input stream that translates bytes to characters
• LineNumberReader----------------------- Input stream that counts lines
• OutputStreamWriter----------------------- Output stream that translates characters to bytes
• PipedReader-------------------- Input pipe
• PipedWriter ----------------------Output pipe
• PrintWriter------------------------- Output stream that contains print( ) and println( )
• PushbackReader-------------------- Input stream that allows characters to be returned to the input stream
Reader Abstract class that describes character stream input
• StringReader----------------------- Input stream that reads from a string
• StringWriter------------------------ Output stream that writes to a string
• Writer------------------------------------ Abstract class that describes character stream output
Predefined streams
• This package defines a class called System, which
encapsulates several aspects of the run-time
environment.
• 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
are typically used to read and write characters from
and to the console.
Reading Console Input
• the only way to perform console input was to use
a byte stream.
• for commercial applications, the preferred
method of reading console input is to use a
character-oriented stream
• Java, console input is accomplished by reading
from System.in. To obtain a characterbased
• stream that is attached to the console, wrap
System.in in a BufferedReader object.
• BufferedReader supports a buffered input stream
BufferedReader
• A commonly used constructor is shown here:
• BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader,
which converts bytes to characters.
To obtain an InputStreamReader object that is linked to
System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
• Because System.in refers to an object of type InputStream, it can be used for inputStream.
• Putting it all together, the following line of code creates a BufferedReader that is connected
to the keyboard:
• BufferedReader br = new BufferedReader(new
• InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console
through System.in.
Reading Characters
• To read a character from a BufferedReader,
use read( ). The version of read( ) that we will
be using is int read( ) throws IOException
• Each time that read( ) is called, it reads a
character from the input stream and returns it
as an integer value. It returns –1 when the end
of the stream is encountered. As you can see,
it can throw an IOException.
• import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Here is a sample run:
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
Q
• This means that no input is actually passed to the program until you
• press enter.
Reading Strings
• To read a string from the keyboard, use the
version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown
here:
String readLine( ) throws IOException
As you can see, it returns a String object.
• The following program demonstrates BufferedReader and the readLine( ) method; the
• program reads and displays lines of text until you enter the word "stop":
• // Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
EXAMPLE PROGRAM
• The next example creates a tiny text editor. It
creates an array of String objects and
• then reads in lines of text, storing each line in
the array. It will read up to 100 lines or until
you enter "stop." It uses a BufferedReader to
read from the console.
• // A tiny editor.
• import java.io.*;
class TinyEdit {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for(int i=0; i<100; i++) {
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
System.out.println("nHere is your file:");
// display the lines
for(int i=0; i<100; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}
}
}
Here is a sample run:
Enter lines of text.
Enter 'stop' to quit.
This is line one.
This is line two.
Java makes working with strings easy.
Just create String objects.
stop
Here is your file:
This is line one.
This is line two.
Writing Console Output
• Console output is most easily accomplished with print( )
and println( ), described earlier,
• which are used in most of the examples in this book. These
methods are defined by the class PrintStream (which is the
type of object referenced by System.out).
• Thus, write( ) can be used to write to the console. The
simplest
form of write( ) defined by PrintStream is shown here:
void write(int byteval)
• This method writes the byte specified by byteval. Although
byteval is declared as an integer, only the low-order eight
bits are written. Here is a short example that uses write( )
to output
• // Demonstrate System.out.write().
• class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('n');
}
}
• You will not often use write( ) to perform console output (although
doing so might be useful in some situations) because print( ) and
println( ) are substantially easier to use.
The PrintWriter Class
• For realworld programs, the recommended method of writing to
the console when using Java is through a PrintWriter stream.
PrintWriter is one of the character-based classes.
• PrintWriter defines several constructors. The one we will use is
shown here:
• PrintWriter(OutputStream outputStream, boolean flushingOn)
• Here, outputStream is an object of type OutputStream, and
flushingOn controls whether Java flushes the output stream every
time a println( ) method (among others) is called.
• If flushingOn is true, flushing automatically takes place. If false,
flushing is not automatic.
• For example, this line of code creates a PrintWriter that is
connected to console output:
• PrintWriter pw = new PrintWriter(System.out, true);
EXAMPLE PRINTWRITER
• The following application illustrates using a PrintWriter to handle console output:
• // Demonstrate PrintWriter
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
The output from this program is shown here:
This is a string
-7
4.5E-7
there is nothing wrong with using System.out to write simple text output to the console when you are learning Java or
debugging your programs. However, usin a PrintWriter makes your real-world applications easier to internationalize
Reading and Writing Files
• Java provides a number of classes and methods that allow
you to read and write files.
• Two of the most often-used stream classes are
FileInputStream and FileOutputStream, which create byte
streams linked to files. To open a file, you simply create an
object of one of these classes, specifying the name of the
file as an argument to the constructor. Although both
classes support additional constructors, the following are
the forms that we will be using:
• FileInputStream(String fileName) throws
FileNotFoundException
• FileOutputStream(String fileName) throws
FileNotFoundException
• fileName specifies the name of the file that you
want to open.
• When you create an input stream, if the file does
not exist, then FileNotFoundException is thrown.
• For outputstreams, if the file cannot be opened
or created, then FileNotFoundException is
thrown.
• FileNotFoundException is a subclass of
IOException. When an output file is opened, any
preexisting file by the same name is destroyed
Close method
• When you are done with a file, you must close it.
This is done by calling the close( ) method, which
is implemented by both FileInputStream and
FileOutputStream.
• It is shown here:
• void close( ) throws IOException
• Closing a file releases the system resources
allocated to the file, allowing them to be used
byanother file. Failure to close a file can result in
“memory leaks” because of unused resources
remaining allocated.
Read method
• To read from a file, you can use a version of
read( ) that is defined within FileInputStream.
The one that we will use is shown here:
• int read( ) throws IOException
• Each time that it is called, it reads a single byte
from the file and returns the byte as an
integer value. read( ) returns –1 when the end
of the file is encountered. It can throw an
IOException.
• The following program uses read( ) to input and display
the contents of a file that
• contains ASCII text. The name of the file is specified as
a command-line argument.
/* Display a text file.
To use this program, specify the name of the file that you
want to see.
For example, to see a file called TEST.TXT,
use the following command line.
• java ShowFile TEST.TXT
*/
To open and read a file
import java.io.*;
class ShowFile {
public static void main(String args[])
{
int i;
FileInputStream fin;
// First, confirm that a filename has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// Attempt to open the file.
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Cannot Open File");
return;
}
// At this point, the file is open and can be read.
// The following reads characters until EOF is encountered.
Cont….
try {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(IOException e) {
System.out.println("Error Reading File");
}
// Close the file.
try {
fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
}
Finally block
• The variation is to call close( ) within a finally
block.
• In this approach, all of the methods that access
the file are contained within a try block, and the
finally block is used to close the file. This way, no
matter how the try block terminates,the file is
closed. Assuming the preceding example, here is
how the try block that reads the
• file can be recoded:
finally
try {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(IOException e) {
System.out.println("Error Reading File");
} finally {
// Close file on the way out of the try block.
try {
fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
• Although not an issue in this case, one advantage
to this approach in general is that if the
code that accesses a file terminates because of
some non-I/O related exception, the file is still
closed by the finally block.
• Sometimes it’s easier to wrap the portions of a
program that open the file and access
• the file within a single try block (rather than
separating the two) and then use a finally block
to close the file.
• /* Display a text file.
To use this program, specify the name
of the file that you want to see.
For example, to see a file called TEST.TXT,
use the following command line.
java ShowFile TEST.TXT
This variation wraps the code that opens and
accesses the file within a single try block.
The file is closed by the finally block.
*/
import java.io.*;
class ShowFile {
public static void main(String args[])
{
int i;
FileInputStream fin = null;
// First, confirm that a filename has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// The following code opens a file, reads characters until EOF
// is encountered, and then closes the file via a finally block.
try {
fin = new FileInputStream(args[0]);
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(FileNotFoundException e) {
System.out.println("File Not Found.");
}
catch(IOException e) {
System.out.println("An I/O Error Occurred");
} finally {
// Close file in all cases.
try {
if(fin != null) fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
}
}
Write method
• To write to a file, you can use the write( ) method
defined by FileOutputStream. Its
• simplest form is shown here:
void write(int byteval) throws IOException
• This method writes the byte specified by byteval
to the file. Although byteval is declared as an
integer, only the low-order eight bits are written
to the file. If an error occurs during writing,
an IOException is thrown. The next example uses
write( ) to copy a file:
Copy a file
• /* Copy a file.
• To use this program, specify the name
• of the source file and the destination file.
• For example, to copy a file called FIRST.TXT
• to a file called SECOND.TXT, use the following
• command line.
• java CopyFile FIRST.TXT SECOND.TXT
• */
example
• import java.io.*;
• class CopyFile {
• public static void main(String args[]) throws IOException
• {
• int i;
• FileInputStream fin = null;
• FileOutputStream fout = null;
• // First, confirm that both files have been specified.
• if(args.length != 2) {
• System.out.println("Usage: CopyFile from to");
• return;
• }
// Copy a File.
try {
// Attempt to open the files.
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException e) {
System.out.println("I/O Error: " + e);
} finally {
try {
if(fin != null) fin.close();
} catch(IOException e2) {
System.out.println("Error Closing Input File");
}
try {
if(fout != null) fout.close();
} catch(IOException e2) {
System.out.println("Error Closing Output File");
}
}
}}
• In the program, notice that two separate try blocks are used when closing the files. This
• ensures that both files are closed, even if the call to fin.close( ) throws an exception.
Automatically Closing a File
• Here is its general form:
try (resource-specification) {
// use the resource
}
• Here, resource-specification is a statement that declares and
initializes a resource, such as a file stream. It consists of a variable
declaration in which the variable is initialized with a reference
to the object being managed.
When the try block ends, the resource is automatically released.
• In the case of a file, this means that the file is automatically closed.
(Thus, there is no need to call close( ) explicitly.) Of course, this
form of try can also include catch and finally clauses.
• This new form of try is called the try-with-resources statement.
/* This version of the ShowFile program uses a try-with-resources
statement to automatically close a file after it is no longer needed.
Note: This code requires JDK 7 or later.
*/
import java.io.*;
class ShowFile {
public static void main(String args[])
{
int i;
// First, confirm that a filename has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// The following code uses a try-with-resources statement to open
// a file and then automatically close it when the try block is left.
try(FileInputStream fin = new FileInputStream(args[0])) {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(FileNotFoundException e) {
System.out.println("File Not Found.");
} catch(IOException e) {
System.out.println("An I/O Error Occurred");
}
}
Copy
• /* A version of CopyFile that uses try-with-resources.
• It demonstrates two resources (in this case files) being
• managed by a single try statement.
• */
• import java.io.*;
• class CopyFile {
• public static void main(String args[]) throws IOException
• {
• int i;
• // First, confirm that both files have been specified.
• if(args.length != 2) {
• System.out.println("Usage: CopyFile from to");
• return;
• }
• // Open and manage two files via the try statement.
• try (FileInputStream fin = new FileInputStream(args[0]);
• FileOutputStream fout = new FileOutputStream(args[1]))
• {
• do {
• i = fin.read();
• if(i != -1) fout.write(i);
• } while(i != -1);
• 318 PART I The Java Language
• } catch(IOException e) {
• System.out.println("I/O Error: " + e);
• }
• }
• }
• In this program, notice how the input and output files are opened within the try block:
• try (FileInputStream fin = new FileInputStream(args[0]);
• FileOutputStream fout = new FileOutputStream(args[1]))
• {
• // ...
• After this try block ends, both fin and fout will have been closed. If you compare this
• version of the program to the previous version, you will see that it is much shorter. The
• ability to streamline source code is a side-benefit of automatic resource management.
API nio(newIO)
• Java 2, version 1.4 added a new way to handle I/O operations. Called the new I/O APIs,
it is one of the more interesting additions that Sun included in the 1.4 release because it
supports a channel-based approach to I/O operations.
The new I/O classes are contained in the five packages shown here.
• Package Purpose
• java.nio --------------------Top-level package for the new I/O system. Encapsulates various types of
buffers which contain data operated upon by the new I/O system.
• java.nio.channels -------------Supports channels, which are essentially open I/O
connections.
• java.nio.channels.spi -----------Supports service providers for channels.
• java.nio.charset --------------------Encapsulates character sets. Also supports encoders
and decoders that convert characters to bytes and bytes to characters, respectively.
• java.nio.charset.spi --------------Supports service providers for character sets.
• NIO classes supplement the standard I/O system, giving you an alternative
approach, which can be beneficial in some circumstances.
NIO FUNDAMENTALS
• The new I/O system is built on two
foundational items: buffers and channels.
• A buffer holds data.
• A channel represents an open connection to
an I/O device, such as a file or a socket.
BUFFERS
• Buffers
• Buffers are defined in the java.nio package. All buffers
are subclasses of the Bufferclass, which defines the
core functionality common to all buffers: current
position,limit, and capacity.
• The current position is the index within the buffer at
which the next read or write operation will take place.
The current position is advanced by most read or write
operations.
• The limit is the index of the end of the buffer.
• The capacity is the number of elements that the buffer
can hold.
BUFFER METHODS
• final int capacity( ) ------Returns the number of elements that the invoking buffer is capable
of holding.
• final Buffer clear( ) -------Clears the invoking buffer and returns a reference to the buffer.
• final Buffer flip( ) ----------Sets the invoking buffer’s limit to the currentposition and resets
the current position to 0.
• Returns a reference to the buffer.
• final boolean hasRemaining( ) --------------Returns true if there are elements remaining in the
invoking buffer. Returns false otherwise.
• abstract boolean isReadOnly( ) ------------------Returns true if the invoking buffer is read-
only. Returns false otherwise.
• final int limit( ) --------------------Returns the invoking buffer’s limit.
• final Buffer limit(int n) -----------------------Sets the invoking buffer’s limit to n. Returns a
reference to the buffer.
• final Buffer mark( ) -------------------Sets the mark and returns a reference to the invoking
buffer.
• final int position( ) ----------------------------Returns the current position.
• final Buffer position(int n) ------------------------Sets the invoking buffer’s current position to
n. Returns a reference to the buffer.
• final Buffer reset( ) -----------------Resets the current position of the invoking buffer to the
previously set mark. Returns a
reference to the buffer.
• final Buffer rewind( ) --------------Sets the position of the invoking buffer to 0. Returns a reference to the
buffer.
BUFFER CLASSES
• From Buffer are derived the following specific buffer classes, which hold the type
• of data that their names imply.
• ByteBuffer
• CharBuffer
• DoubleBuffer
• FloatBuffer
• IntBuffer
• LongBuffer
• MappedByteBuffer
• ShortBuffer
• MappedByteBuffer is a subclass of ByteBuffer that is used to map a file to a buffer.
• All buffers support various get( ) and put( ) methods, which allow you to get data
• from a buffer or put data into a buffer.
BYTE BUFFER METHODS
• METHOD:
• abstract byte get( ) ------Returns the byte at the
current position.
• ByteBuffer get(byte vals[ ] )---- Copies the
invoking buffer into the array referred to by vals.
Returns a reference to the buffer.
• final ByteBuffer put(byte vals[ ] ) -----Copies all
elements of vals into the invoking buffer,
beginning at the currentposition. Returns a
reference to the buffer.
CHANNELS
• Channels are defined in java.nio.channels. A
channel represents an open connection to an
• I/O source or destination. You obtain a
channel by calling getChannel( ) on an object
that supports channels.
Channel classes
getChannel( ) to the following I/O classes.
FileInputStream
FileOutputStream
RandomAccessFile
socket
ServerSocket
DatagramSocket
• Thus, to obtain a channel, you first obtain an object of one of these classes and then call
getChannel( ) on that object.
The specific type of channel returned depends upon the type of object getChannel( ) is called on. For
example, when called on a FileInputStream, FileOuputStream, or
RandomAccessFile, getChannel( ) returns a channel of type FileChannel.
When calledon a Socket, getChannel( ) returns a SocketChannel.
Channels such as FileChannel and SocketChannel support various read( ) and
• write( ) methods that enable you to perform I/O operations through the channel.
Forexample, here are a few of the read( ) and write( ) methods defined for FileChannel
Channel methods
• abstract int read(ByteBuffer bb) Reads bytes
from the invoking channel into bbuntil the
buffer is full, or there is no more input.Returns
the number of bytes actually read.
• abstract int write(ByteBuffer bb) Writes the
contents of bb to the invoking channel,
starting at the current position. Returns the
number of bytes written.
Charset and selectors
• Charsets and Selectors
• Two other entities used by NIO are charsets and selectors.
• A charset defines the way that bytes are mapped to characters. You
can encode a sequence of characters into bytes using an encoder.
You can decode a sequence of bytes into characters using a
decoder. Charsets, encoders, and decoders are supported by classes
defined in the
• java.nio.charset package. Because default encoders and decoders
are provided, you will not often need to work explicitly with
charsets.
• A selector supports key-based, non-blocking, multiplexed I/O. In
other words, selectors enable you to perform I/O through multiple
channels. Selectors are supported by classes defined in the
java.nio.channels package. Selectors are most
applicable to socket-backed channels.
Reading a File
• read a file using a channel and a manually allocated buffer, follow this procedure.
• First open the file for input using FileInputStream. Then, obtain a channel to this file
by calling getChannel( ). It has this general form:
• FileChannel getChannel( )
It returns a FileChannel object, which encapsulates the channel for file operations. Once
• a file channel has been opened, obtain the size of the file by calling size( ), shown here:
long size( ) throws IOException
• It returns the current size, in bytes, of the channel, which reflects the underlying file.
• Next, call allocate( ) to allocate a buffer large enough to hold the file’s contents. Because
file channels operate on byte buffers you will use the allocate( ) method defined by
ByteBuffer.
• It has this general form.
• static ByteBuffer allocate(int cap)
Reading a file
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class ExplicitChannelRead {
public static void main(String args[])
FileInputStream fIn;
FileChannel fChan;
long fSize;
ByteBuffer mBuf;
try
// First, open a file for input.
fIn = new FileInputStream("test.txt");
// Next, obtain a channel to that file.
fChan = fIn.getChannel();
// Now, get the file's size.
fSize = fChan.size();
// Allocate a buffer of the necessary size.
mBuf = ByteBuffer.allocate((int)fSize);
// Read the file into the buffer.
fChan.read(mBuf);
// Rewind the buffer so that it can be read.
mBuf.rewind();
// Read bytes from the buffer.
for(int i=0; i < fSize; i++)
System.out.print((char)mBuf.get());
System.out.println();
fChan.close(); // close channel
fIn.close(); // close file
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
}
}
Map method
• The map( ) method is shown here:
• MappedByteBuffer map(FileChannel.MapMode
how,long pos, long size) throws IOException
• The map( ) method causes the data in the file to be
mapped into a buffer in memory.
• The value in how determines what type of operations
are allowed. It must be one of these values.
• MapMode.READ
• MapMode.READ_WRITE
• MapMode.PRIVATE
Using map to read a file
• The following program reworks the first example so that it uses a mapped file.
// Use a mapped file to read a text file.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class MappedChannelRead {
public static void main(String args[]) {
FileInputStream fIn;
FileChannel fChan;
long fSize;
MappedByteBuffer mBuf;
try {
// First, open an file for input.
fIn = new FileInputStream("test.txt");
// Next, obtain a channel to that file.
fChan = fIn.getChannel();
// Get the size of the file.
fSize = fChan.size();
// Now, map the file into a buffer.
mBuf = fChan.map(FileChannel.MapMode.READ_ONLY,
0, fSize);
// Read bytes from the buffer.
for(int i=0; i < fSize; i++)
System.out.print((char)mBuf.get());
fChan.close(); // close channel
fIn.close(); // close file
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
}
}
Writing to a File
• There are several ways to write to a file through a channel. Again,
we will look at two. First, you can write data to an output file
through a channel, by using explicit write operations.
• Second, if the file is opened for read/write operations, you can
map the file to a buffer and then write to that buffer. Changes to
the buffer will automatically be reflected in the file. Both ways are
described here.
• To write to a file through a channel using explicit calls to write( ),
follow these steps. First, open the file for output. Then, allocate a
byte buffer, put the data you want to write into that buffer, and
then called write( ) on the channel.
• The following program demonstrates this procedure. It writes the
alphabet to a file called test.txt.
// Write to a file using the new I/O.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class ExplicitChannelWrite {
public static void main(String args[]) {
FileOutputStream fOut;
FileChannel fChan;
ByteBuffer mBuf;
try {
fOut = new FileOutputStream("test.txt");
// Get a channel to the output file.
fChan = fOut.getChannel();
// Create a buffer.
mBuf = ByteBuffer.allocateDirect(26);
// Write some bytes to the buffer.
for(int i=0; i<26; i++)
mBuf.put((byte)('A' + i));
// Rewind the buffer so that it can written.
mBuf.rewind();
// Write the buffer to the output file.
fChan.write(mBuf);
// close channel and file.
fChan.close();
fOut.close();
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
}
}
Map method for write
• To write to a file using a mapped file, follow these
steps. First, open the file for
• read/write operations. Next, map that file to a
buffer by calling map( ). Then, write to the buffer.
Because the buffer is mapped to the file, any
changes to that buffer are automatically reflected
in the file.
• Thus, no explicit write operations to the channel
are necessary. Here is the preceding program
reworked so that a mapped file is used.
Map method
// Write to a mapped file.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class MappedChannelWrite {
856 J a v a ™ 2 : T h e C o m p l e t e R e f e r e n c e
public static void main(String args[]) {
RandomAccessFile fOut;
FileChannel fChan;
ByteBuffer mBuf;
try {
fOut = new RandomAccessFile("test.txt", "rw");
// Next, obtain a channel to that file.
fChan = fOut.getChannel();
// Then, map the file into a buffer.
mBuf = fChan.map(FileChannel.MapMode.READ_WRITE,
0, 26);
// Write some bytes to the buffer.
for(int i=0; i<26; i++)
mBuf.put((byte)('A' + i));
// close channel and file.
fChan.close();
fOut.close();
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
}
Copying a File Using the New I/O
• The new I/O system simplifies some types of
file operations. For example, the following
program copies a file. It does so by opening an
input channel to the source file and an output
channel to the target file. It then writes the
mapped input buffer to the output file in a
single operation.
Copy
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class NIOCopy {
public static void main(String args[]) {
FileInputStream fIn;
FileOutputStream fOut;
FileChannel fIChan, fOChan;
long fSize;
MappedByteBuffer mBuf;
try {
fIn = new FileInputStream(args[0]);
fOut = new FileOutputStream(args[1]);
// Get channels to the input and output files.
fIChan = fIn.getChannel();
fOChan = fOut.getChannel();
// Get the size of the file.
fSize = fIChan.size();
// Map the input file to a buffer.
mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY,
0, fSize);
copy
// Write the buffer to the output file.
fOChan.write(mBuf); // this copies the file
// Close the channels and files.
fIChan.close();
fIn.close();
fOChan.close();
fOut.close();
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
} catch (ArrayIndexOutOfBoundsException exc) {
System.out.println("Usage: Copy from to");
858 J a v a ™ 2 : T h e C o m p l e t e R e f e r e n c e
System.exit(1);
}
}
}

unit 2 java.pptx

  • 1.
    • A classto display a simple message: class MyProgram { public static void main(String[] args) { System.out.println(“First Java program."); } } Simple Java Program
  • 2.
    • Real worldobjects are things that have: 1) state 2) behavior Example: your dog: • state – name, color, breed, sits?, barks?, wages tail?, runs? • behavior – sitting, barking, waging tail, running • A software object is a bundle of variables (state) and methods (operations). What is an Object?
  • 3.
    • A classis a blueprint that defines the variables and methods common to all objects of a certain kind. • Example: ‘your dog’ is a object of the class Dog. • An object holds values for the variables defines in the class. • An object is called an instance of the Class What is a Class?
  • 4.
    • A variableis declared to refer to the objects of type/class String: String s; • The value of s is null; it does not yet refer to any object. • A new String object is created in memory with initial “abc” value: • String s = new String(“abc”); • Now s contains the address of this new object. Object Creation
  • 5.
    • A programaccumulates memory through its execution. • Two mechanism to free memory that is no longer need by the program: 1) manual – done in C/C++ 2) automatic – done in Java • In Java, when an object is no longer accessible through any variable, it is eventually removed from the memory by the garbage collector. • Garbage collector is parts of the Java Run-Time Environment. Object Destruction
  • 6.
    • A basisfor the Java language. • Each concept we wish to describe in Java must be included inside a class. • A class defines a new data type, whose values are objects: • A class is a template for objects • An object is an instance of a class Class
  • 7.
     A classcontains a name, several variable declarations (instance variables) and several method declarations. All are called members of the class.  General form of a class: class classname { type instance-variable-1; … type instance-variable-n; type method-name-1(parameter-list) { … } type method-name-2(parameter-list) { … } … type method-name-m(parameter-list) { … } } Class Definition
  • 8.
    class Box { doublewidth; double height; double depth; } class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20; mybox.depth = 15; vol = mybox.width * mybox.height * mybox.depth; System.out.println ("Volume is " + vol); } } Example: Class Usage
  • 9.
    // This programdeclares two Box objects. class Box { double width; double height; double depth; } class BoxDemo2 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // compute volume of first box vol = mybox1.width * mybox1.height * mybox1.depth; System.out.println("Volume is " + vol); // compute volume of second box vol = mybox2.width * mybox2.height * mybox2.depth; System.out.println("Volume is " + vol); } }
  • 10.
    • A constructorinitializes the instance variables of an object. • It is called immediately after the object is created but before the new operator completes. 1) it is syntactically similar to a method: 2) it has the same name as the name of its class 3) it is written without return type; the default return type of a class • constructor is the same class • When the class has no constructor, the default constructor automatically initializes all its instance variables with zero. Constructor
  • 11.
    class Box { doublewidth; double height; double depth; Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } double volume() { return width * height * depth; } } Example: Constructor
  • 12.
    class Box { doublewidth; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { return width * height * depth; } } Parameterized Constructor
  • 13.
     General formof a method definition: type name(parameter-list) { … return value; … }  Components: 1) type - type of values returned by the method. If a method does not return any value, its return type must be void. 2) name is the name of the method 3) parameter-list is a sequence of type-identifier lists separated by commas 4) return value indicates what value is returned by the method. Methods
  • 14.
    • Classes declaremethods to hide their internal data structures, as well as for their own internal use: Within a class, we can refer directly to its member variables: class Box { double width, height, depth; void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } Example: Method
  • 15.
    • Parameters increasegenerality and applicability of a method: • 1) method without parameters int square() { return 10*10; } • 2) method with parameters int square(int i) { return i*i; } • Parameter: a variable receiving value at the time the method is invoked. • Argument: a value passed to the method when it is invoked. Parameterized Method
  • 16.
    Access Control: DataHiding and Encapsulation • Java provides control over the visibility of variables and methods. • Encapsulation, safely sealing data within the capsule of the class Prevents programmers from relying on details of class implementation, so you can update without worry • Helps in protecting against accidental or wrong usage. • Keeps code elegant and clean (easier to maintain)
  • 17.
    Access Modifiers: Public,Private, Protected • Public: keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. • Default(No visibility modifier is specified): it behaves like public in its package and private in other packages. • Default Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible.
  • 18.
    • Private fieldsor methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. • Protected members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class.
  • 19.
    Visibility public class Circle{ private double x,y,r; // Constructor public Circle (double x, double y, double r) { this.x = x; this.y = y; this.r = r; } //Methods to return circumference and area public double circumference() { return 2*3.14*r;} public double area() { return 3.14 * r * r; } }
  • 20.
    Keyword this • Canbe used by any object to refer to itself in any class method • Typically used to – Avoid variable name collisions – Pass the receiver as an argument – Chain constructors
  • 21.
    • Keyword thisallows a method to refer to the object that invoked it. • It can be used inside any method to refer to the current object: Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; } Keyword this
  • 22.
    • Garbage collectionis a mechanism to remove objects from memory when they are no longer needed. • Garbage collection is carried out by the garbage collector: • 1) The garbage collector keeps track of how many references an object has. • 2) It removes an object from memory when it has no longer any references. • 3) Thereafter, the memory occupied by the object can be allocated again. • 4) The garbage collector invokes the finalize method. Garbage Collection
  • 23.
    • A constructorhelps to initialize an object just after it has been created. • In contrast, the finalize method is invoked just before the object is destroyed: • 1) implemented inside a class as: protected void finalize() { … } • 2) implemented when the usual way of removing objects from memory is insufficient, and some special actions has to be carried out finalize() Method
  • 24.
    • It islegal for a class to have two or more methods with the same name. • However, Java has to be able to uniquely associate the invocation of a method with its definition relying on the number and types of arguments. • Therefore the same-named methods must be distinguished: • 1) by the number of arguments, or • 2) by the types of arguments • Overloading and inheritance are two ways to implement polymorphism. Method Overloading
  • 25.
    class OverloadDemo { voidtest() { System.out.println("No parameters"); } void test(int a) { System.out.println("a: " + a); } void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } double test(double a) { System.out.println("double a: " + a); return a*a; } } Example: Overloading
  • 26.
    class Box { doublewidth, height, depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width = -1; height = -1; depth = -1; } Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; } } Constructor Overloading
  • 27.
    • Two typesof variables: 1) simple types 2) class types • Two corresponding ways of how the arguments are passed to methods: • 1) by value a method receives a cope of the original value; parameters of simple types • 2) by reference a method receives the memory address of the original value, not the value itself; parameters of class types Parameter Passing
  • 28.
    class CallByValue { publicstatic void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.print("a and b before call: “); System.out.println(a + " " + b); ob.meth(a, b); System.out.print("a and b after call: "); System.out.println(a + " " + b); } } Call by value
  • 29.
    • As theparameter hold the same address as the argument, changes to the object inside the method do affect the object used by the argument: class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.print("ob.a and ob.b before call: “); System.out.println(ob.a + " " + ob.b); ob.meth(ob); System.out.print("ob.a and ob.b after call: "); System.out.println(ob.a + " " + ob.b); } } Call by refference
  • 30.
    • A recursivemethod is a method that calls itself: 1) all method parameters and local variables are allocated on the stack 2) arguments are prepared in the corresponding parameter positions 3) the method code is executed for the new arguments 4) upon return, all parameters and variables are removed from the stack 5) the execution continues immediately after the invocation point Recursion
  • 31.
    class Factorial { intfact(int n) { if (n==1) return 1; return fact(n-1) * n; } } class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.print("Factorial of 5 is "); System.out.println(f.fact(5)); } } Example: Recursion
  • 32.
    • String isprobably the most commonly used class in Java's class library. The obvious reason for this is that strings are a very important part of programming. • The first thing to understand about strings is that every string you create is actually an object of type String. Even string constants are actually String objects. • For example, in the statement System.out.println("This is a String, too"); the string "This is a String, too" is a String constant String Handling
  • 33.
    • Java definesone operator for String objects: +. • It is used to concatenate two strings. For example, this statement • String myString = "I" + " like " + "Java."; results in myString containing "I like Java."
  • 34.
    • The Stringclass contains several methods that you can use. Here are a few. You can • test two strings for equality by using equals( ). You can obtain the length of a string by calling the length( ) method. You can obtain the character at a specified index within a string by calling charAt( ). The general forms of these three methods are shown here: • // Demonstrating some String methods. class StringDemo2 { public static void main(String args[]) { String strOb1 = "First String"; String strOb2 = "Second String"; String strOb3 = strOb1; System.out.println("Length of strOb1: " + strOb1.length());
  • 35.
    System.out.println ("Char atindex 3 in strOb1: " + strOb1.charAt(3)); if(strOb1.equals(strOb2)) System.out.println("strOb1 == strOb2"); else System.out.println("strOb1 != strOb2"); if(strOb1.equals(strOb3)) System.out.println("strOb1 == strOb3"); else System.out.println("strOb1 != strOb3"); } } This program generates the following output: Length of strOb1: 12 Char at index 3 in strOb1: s strOb1 != strOb2 strOb1 == strOb3
  • 36.
    Argument Passing call-by-value call-by-value copiesthe value of an argument into the formal parameter of the subroutine. Changes made to the parameter of the subroutine have no effect on the argument. call-by-reference call-by-reference , a reference to an argument (not the value of the argument) is passed to the parameter. Changes made to the parameter will affect the argument used to call the subroutine. As you will see, Java uses both approaches, depending upon what is passed.
  • 42.
    Encapsulation provides anotherimportant attribute: access control. Encapsulation - control what parts of a program can access the members of a class. Prevent misuse. Java’s access specifiers are public, private, and protected Java also defines a default access level. protected applies only when inheritance is involved. When a member of a class is modified by the public specifier, then that member can be accessed by any other code. When a member of a class is specified as private, then that member can only be accessed by other members of its class.
  • 44.
    Static - Whena member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. Both methods and variables to be static. The most common example of a static member is main( ). Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. Methods declared as static have several restrictions: They can only call other static methods. They must only access static data. They cannot refer to this or super in any way.
  • 46.
    Call a staticmethod from outside its class, general form: classname.method( )
  • 47.
    The final keywordin java is used to restrict the user. Final can be: variable method Class Final Variable Variable as final, you cannot change the value of final variable(It will be constant). class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } }
  • 48.
    Java final method Ifyou make any method as final, you cannot override it. class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Final method is inherited but you cannot override it class Bike{ final void run(){System.out.println("running...");} } class Honda2 extends Bike{ public static void main(String args[]){ new Honda2().run(); } }
  • 49.
    Java final class Ifyou make any class as final, you cannot extend it. final class Bike{} class Honda1 extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda1 honda= new Honda(); honda.run(); } }
  • 60.
    String String is asequence of characters. Other languages that implement strings as character arrays Java implements strings as objects of type String. Once a String object has been created, you cannot change the characters that comprise that string Java provides two options: StringBuffer and StringBuilder. Both hold strings that can be modified after they are created. The strings within objects of type String are unchangeable means that the contents of the String instance cannot be changed after it has been created. A variable declared as a String reference can be changed to point at some other String object at any time.
  • 61.
    The String Constructors Tocreate an empty String String s = new String(); you will want to create strings that have initial values String(char chars[ ]) char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); You can specify a subrange of a character array as an initializer using the following constructor: String(char chars[ ], int startIndex, int numChars) char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3);
  • 62.
    You can constructa String object that contains the same character sequence as another String object using this constructor: String(String strObj)
  • 64.
    String Constructors Addedby J2SE 5 String(int codePoints[ ], int startIndex, int numChars) codePoints is an array that contains Unicode code points String(StringBuilder strBuildObj) String Length int length( ) char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length()); Special String Operations The automatic creation of new String instances from string literals  Concatenation of multiple String objects by use of the + operator, The conversion of other data types to a string representation. There are explicit methods available to perform all of these funtions, but Java does them automatically as a convenience for the programmer
  • 65.
    String Literals char chars[]= { 'a', 'b', 'c' }; String s1 = new String(chars); String s2 = "abc"; you can call methods directly on a quoted string as if it were an object reference, as the following statement shows. System.out.println("abc".length()); String Concatenation String age = "9"; String s = "He is " + age + " years old."; System.out.println(s);
  • 66.
    String Concatenation withOther Data Types int age = 9; String s = "He is " + age + " years old."; System.out.println(s); String s = "four: " + 2 + 2; System.out.println(s); This fragment displays four: 22 rather than the four: 4 To complete the integer addition first, you must use parentheses, like this: String s = "four: " + (2 + 2); Now s contains the string “four: 4”.
  • 67.
    String Conversion andtoString( ) // Override toString() for Box class. class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } public String toString() { return "Dimensions are " + width + " by " + depth + " by " + height + "."; } } class toStringDemo { public static void main(String args[]) { Box b = new Box(10, 12, 14); String s = "Box b: " + b; // concatenate Box object System.out.println(b); // convert Box to string System.out.println(s); } }
  • 96.
    Naming conventions • Javanaming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method etc. • But, it is not forced to follow. So, it is known as convention not rule. • All the classes, interfaces, packages, methods and fields of java programming language are given according to java naming convention.
  • 97.
    Advantage of namingconventions in java • By using standard Java naming conventions, you make your code easier to read for yourself and for other programmers. • Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.
  • 98.
    convention Name Convention class nameshould start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc. interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc. method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc. variable name should start with lowercase letter e.g. firstName, orderNumber etc. package name should be in lowercase letter e.g. java, lang, sql, util etc. constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
  • 99.
    Java bean A JavaBean is a java class that should follow following conventions: It should have a no-arg constructor. It should be Serializable. It should provide methods to set and get the values of the properties, known as getter and setter methods.
  • 100.
    Why use JavaBean? • According to Java white paper, it is a reusable software component. • A bean encapsulates many objects into one object, so we can access this object from multiple places. • Moreover, it provides the easy maintenance.
  • 101.
    Definitions • A reusablesoftware component that can be manipulated visually in a ‘builder tool’. (from JavaBean Specification) • The JavaBeans API provides a framework for defining reusable, embeddable, modular software components.
  • 102.
    Simple example ofjava bean class //employee.java Package mypack; Public class employee implementsjava.io.serializiable { private int id; private string name; public employee() { }
  • 103.
    public void setId(intid) { this.id=id; } public int getId() { Return id; }
  • 104.
    Public void setName(Stringname) { This.name=name; } Public string getName() { Return name; } } How to access the java bean class? Package mypack; Public class test { Public static void main(string args[]) { Employee e=new employee(); e.setName(“Arjun”); System.out.println(e.getName()); e.setId(10112); System.out.println(e.getId()); } }
  • 105.
    Advantages of JavaBeans • The following list enumerates some of the benefits that Java Bean technology provides for a component developer: • • A Bean obtains all the benefits of Java’s “write-once, run- anywhere” paradigm. • The properties, events, and methods of a Bean that are exposed to another application can be controlled. • • Auxiliary software can be provided to help configure a Bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment. • • The state of a Bean can be saved in persistent storage and restored at a later time. • • A Bean may register to receive events from other objects and can generate events that are sent to other objects.
  • 106.
    Introspection • At thecore of Java Beans is introspection. This is the process of analyzing a Bean to determine its capabilities. • This is an essential feature of the Java Beans API because it allows another application, such as a design tool, to obtain information about a component. Without introspection, the Java Beans technology could not operate.
  • 107.
    Design Patterns forProperties • A property is a subset of a Bean’s state. The values assigned to the properties determine the behavior and appearance of that component. A property is set through a setter method. • property is obtained by a getter method. There are two types of properties: simple and indexed
  • 108.
    Simple property • Asimple property has a single value. It can be identified by the following design patterns, • where N is the name of the property and T is its type: • public T getN( ) • public void setN(T arg) • A read/write property has both of these methods to access its values. • A read-only property has only a get method. A write-only property has only a set method.
  • 109.
    Simple property • privatedouble depth, height, width; • public double getDepth( ) { • return depth; • } • public void setDepth(double d) { • depth = d; • } • public double getHeight( ) { • return height; • } • public void setHeight(double h) { • height = h; • } • public double getWidth( ) { • return width; • } • public void setWidth(double w) { • width = w; • }
  • 110.
    • An indexedproperty consists of multiple values. It can be identified by the following design • patterns, where N is the name of the property and T is its type: • public T getN(int index); • public void setN(int index, T value); • public T[ ] getN( ); • public void setN(T values[ ]);
  • 111.
    Indexed property • Hereis an indexed property called data along with its getter and setter methods: • private double data[ ]; • public double getData(int index) { • return data[index]; • } • public void setData(int index, double value) { • data[index] = value; • } • public double[ ] getData( ) { • return data; • } • public void setData(double[ ] values) { • data = new double[values.length]; • System.arraycopy(values, 0, data, 0, values.length); • }
  • 112.
    Bound and ConstrainedProperties • A Bean that has a bound property generates an event when the property is changed. Theevent is of type PropertyChangeEvent and is sent to objects that previously registered an interest in receiving such notifications. A class that handles this event must implement the • PropertyChangeListener interface. • A Bean that has a constrained property generates an event when an attempt is made tochange its value. It also generates an event of type PropertyChangeEvent
  • 113.
    beaninfo • The BeanInfointerface enables you to explicitly control what • information is available. • The BeanInfo interface defines several methods, including these: PropertyDescriptor[ ] getPropertyDescriptors( ) EventSetDescriptor[ ] getEventSetDescriptors( ) MethodDescriptor[ ] getMethodDescriptors( ) They return arrays of objects that provide information about the properties, events, and methods of a Bean. The classes PropertyDescriptor, EventSetDescriptor, and MethodDescriptor are defined within the java.beans package, and they describe the indicated elements. By implementing these methods, a developer can designate exactly what is presented to a user, bypassing introspection based on design patterns. When creating a class that implements BeanInfo, you must call that class bnameBeanInfo, where bname is the name of the Bean. For example, if the Bean is called MyBean, then the information class must be called MyBeanBeanInfo.
  • 114.
    Persistence • Persistence isthe ability to save the current state of a Bean, including the values of a Bean’s properties and instance variables, to nonvolatile storage and to retrieve them at a later time. • The object serialization capabilities provided by the Java class libraries are used to provide persistence for Beans. • The easiest way to serialize a Bean is to have it implement the java.io.Serializable • interface, which is simply a marker interface. Implementing java.io.Serializable makes • serialization automatic.
  • 115.
    Customizers • A Beandeveloper can provide a customizer that helps another developer configure the Bean. • A customizer can provide a step-by-step guide through the process that must be followed to use the component in a specific context.
  • 116.
    Intro to JavaBeans •What are JavaBeans? – Software components written in Java – Connect and Configure Components – Builder Tools allow connection and configuration of Beans – Begins ‘Age of Component Developer’ – Bringing Engineering methods to Software Engineering (e.g. electronics…)
  • 117.
    The JavaBeans API •Features implemented as extensions to standard Java Class Library • Main Component Services – GUI merging – Persistence – Event Handling – Introspection – Application Builder Support
  • 118.
    User Interface Merging •Containers usually have Menus and/or toolbars • Allows components to add features to the menus and/or toolbars • Define mechanism for interface layout between components and containers
  • 119.
    Persistence • Components canbe stored and retrieved • Default – inherit serialization • Can define more complex solutions based on needs of the components
  • 120.
    Event Handling • Defineshow components interact • Java AWT event model serves as basis for the event handling API’s • Provides a consistent way for components to interact with each other
  • 121.
    Introspection • Defines techniquesso components can expose internal structure at design time • Allows development tools to query a component to determine member variables, methods, and interfaces • Standard naming patterns used • Based on java.lang.reflect
  • 122.
    Application Builder Support •Provides support for manipulating and editing components at design time • Used by tools to provide layout and customizing during design • Should be separate from component • Not needed at run time
  • 123.
    Bean Requirements • Introspection –Exports: properties, methods, events • Properties – Subset of components internal state • Methods – Invoked to execute component code • Events (If any needed) – Notification of a change in state – User activities (typing, mouse actions, …)
  • 124.
    Bean Requirements • Customization –Developer can change appearance • Persistence – Save current state so it can be reloaded
  • 125.
    Other properties • Indexedproperties – Array value with get and set elements • Bound properties – Triggers event when value changed • Constrained properties – Triggers event when value changes and allows listeners to ‘veto’ the change
  • 126.
    BeanInfo class • Providesmore information using FeatureDescripter objects • Subclasses: – BeanDescripter, PropertyDescripter, IndexedPropertyDescripter, EventSetDescripter, MethodDescripter, ParameterDescripter
  • 127.
    BeanInfo class • ICONto represent Bean • Customizer Class (wizard for set up) • Property Editor references • List of properties with descriptions • List of methods with descriptions • Method to reset properties to defaults
  • 128.
    The beanbox • Primarytask is setting property values • Property editors for common types – Set Font – Set background/foreground colors – Set numeric values – Set string values
  • 129.
    I/O basics • Theio package supports Java’s basic I/O (input/out • Java does provide strong, flexible support for I/O as it relates to files and networks. Java’s I/O system is cohesive and consistent. • In fact, once you understand its fundamentals, the rest of the I/O system is easy to masterput) system, including file I/O.
  • 130.
    STREAMS • A streamis an abstraction that either produces or consumes information. • A stream is linked to a physical device by the Java I/O system. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket • Likewise, an output stream may refer to the console, a disk file, or a network connection.. Java implements streams within class hierarchies defined in the • java.io package.
  • 131.
    BYTE AND CHARACTERSTREAMS • Java defines two types of streams: byte and character. • Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. • Character streams provide a convenient means for handling input and output of characters.
  • 132.
    The Byte StreamClasses • The Byte Stream Classes • Byte streams are defined by using two class hierarchies. At the top are two abstract classes: • InputStream and OutputStream. Each of these abstract classes has several concrete subclasses that handle the differences among various devices, such as disk files, network • connections, and even memory buffers.
  • 133.
    BYTE STREAM CLASSESIN java.io • Stream Class Meaning • BufferedInputStream---------- Buffered input stream • BufferedOutputStream----------- Buffered output stream • ByteArrayInputStream -------------Input stream that reads from a byte array • ByteArrayOutputStream----------- Output stream that writes to a byte array • DataInputStream --------------An input stream that contains methods for reading the Java standard data types • DataOutputStream------------------ An output stream that contains methods for writing the Java standard data types • FileInputStream-------------------- Input stream that reads from a file • FileOutputStream ------------------------Output stream that writes to a file • FilterInputStream------------------------- Implements InputStream • FilterOutputStream ---------------------Implements OutputStream • InputStream ---------------------Abstract class that describes stream input • ObjectInputStream ---------------------Input stream for objects • ObjectOutputStream-------------------- Output stream for objects • OutputStream -----------------------Abstract class that describes stream output • PipedInputStream------------------------------ Input pipe • PipedOutputStream---------------------- Output pipe • PrintStream -------------------Output stream that contains print( ) and println( ) • PushbackInputStream ------------Input stream that supports one-byte “unget,” which returns a byte to the input stream • SequenceInputStream----------------------- Input stream that is a combination of two or more input streams that will be read sequentially, one after the other
  • 134.
    Character stream classes •The Character Stream Classes • Character streams are defined by using two class hierarchies. At the top are two abstract • classes: Reader and Writer. These abstract classes handle Unicode character streams. Java has several concrete subclasses of each of these
  • 135.
    Character stream classes •Stream Class Meaning • BufferedReader --------------Buffered input character stream • BufferedWriter----------------- Buffered output character stream • CharArrayReader---------------- Input stream that reads from a character array • CharArrayWriter------------------ Output stream that writes to a character array • FileReader-------------------------- Input stream that reads from a file • FileWriter ---------------------------Output stream that writes to a file • FilterReader------------------------- Filtered reader • FilterWriter--------------------------- Filtered writer • InputStreamReader------------------ Input stream that translates bytes to characters • LineNumberReader----------------------- Input stream that counts lines • OutputStreamWriter----------------------- Output stream that translates characters to bytes • PipedReader-------------------- Input pipe • PipedWriter ----------------------Output pipe • PrintWriter------------------------- Output stream that contains print( ) and println( ) • PushbackReader-------------------- Input stream that allows characters to be returned to the input stream Reader Abstract class that describes character stream input • StringReader----------------------- Input stream that reads from a string • StringWriter------------------------ Output stream that writes to a string • Writer------------------------------------ Abstract class that describes character stream output
  • 136.
    Predefined streams • Thispackage defines a class called System, which encapsulates several aspects of the run-time environment. • 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.
  • 137.
    • System.out refersto 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 are typically used to read and write characters from and to the console.
  • 138.
    Reading Console Input •the only way to perform console input was to use a byte stream. • for commercial applications, the preferred method of reading console input is to use a character-oriented stream • Java, console input is accomplished by reading from System.in. To obtain a characterbased • stream that is attached to the console, wrap System.in in a BufferedReader object. • BufferedReader supports a buffered input stream
  • 139.
    BufferedReader • A commonlyused constructor is shown here: • BufferedReader(Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream) • Because System.in refers to an object of type InputStream, it can be used for inputStream. • Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: • BufferedReader br = new BufferedReader(new • InputStreamReader(System.in)); After this statement executes, br is a character-based stream that is linked to the console through System.in.
  • 140.
    Reading Characters • Toread a character from a BufferedReader, use read( ). The version of read( ) that we will be using is int read( ) throws IOException • Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns –1 when the end of the stream is encountered. As you can see, it can throw an IOException.
  • 141.
    • import java.io.*; classBRRead { public static void main(String args[]) throws IOException { char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters, 'q' to quit."); // read characters do { c = (char) br.read(); System.out.println(c); } while(c != 'q'); } } Here is a sample run: Enter characters, 'q' to quit. 123abcq 1 2 3 a b c Q • This means that no input is actually passed to the program until you • press enter.
  • 142.
    Reading Strings • Toread a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its general form is shown here: String readLine( ) throws IOException As you can see, it returns a String object.
  • 143.
    • The followingprogram demonstrates BufferedReader and the readLine( ) method; the • program reads and displays lines of text until you enter the word "stop": • // Read a string from console using a BufferedReader. import java.io.*; class BRReadLines { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop")); } }
  • 144.
    EXAMPLE PROGRAM • Thenext example creates a tiny text editor. It creates an array of String objects and • then reads in lines of text, storing each line in the array. It will read up to 100 lines or until you enter "stop." It uses a BufferedReader to read from the console.
  • 145.
    • // Atiny editor. • import java.io.*; class TinyEdit { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[] = new String[100]; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); for(int i=0; i<100; i++) { str[i] = br.readLine(); if(str[i].equals("stop")) break; } System.out.println("nHere is your file:"); // display the lines for(int i=0; i<100; i++) { if(str[i].equals("stop")) break; System.out.println(str[i]); } } } Here is a sample run: Enter lines of text. Enter 'stop' to quit. This is line one. This is line two. Java makes working with strings easy. Just create String objects. stop Here is your file: This is line one. This is line two.
  • 146.
    Writing Console Output •Console output is most easily accomplished with print( ) and println( ), described earlier, • which are used in most of the examples in this book. These methods are defined by the class PrintStream (which is the type of object referenced by System.out). • Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here: void write(int byteval) • This method writes the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Here is a short example that uses write( ) to output
  • 147.
    • // DemonstrateSystem.out.write(). • class WriteDemo { public static void main(String args[]) { int b; b = 'A'; System.out.write(b); System.out.write('n'); } } • You will not often use write( ) to perform console output (although doing so might be useful in some situations) because print( ) and println( ) are substantially easier to use.
  • 148.
    The PrintWriter Class •For realworld programs, the recommended method of writing to the console when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. • PrintWriter defines several constructors. The one we will use is shown here: • PrintWriter(OutputStream outputStream, boolean flushingOn) • Here, outputStream is an object of type OutputStream, and flushingOn controls whether Java flushes the output stream every time a println( ) method (among others) is called. • If flushingOn is true, flushing automatically takes place. If false, flushing is not automatic. • For example, this line of code creates a PrintWriter that is connected to console output: • PrintWriter pw = new PrintWriter(System.out, true);
  • 149.
    EXAMPLE PRINTWRITER • Thefollowing application illustrates using a PrintWriter to handle console output: • // Demonstrate PrintWriter import java.io.*; public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw = new PrintWriter(System.out, true); pw.println("This is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); } } The output from this program is shown here: This is a string -7 4.5E-7 there is nothing wrong with using System.out to write simple text output to the console when you are learning Java or debugging your programs. However, usin a PrintWriter makes your real-world applications easier to internationalize
  • 150.
    Reading and WritingFiles • Java provides a number of classes and methods that allow you to read and write files. • Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files. To open a file, you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor. Although both classes support additional constructors, the following are the forms that we will be using: • FileInputStream(String fileName) throws FileNotFoundException • FileOutputStream(String fileName) throws FileNotFoundException
  • 151.
    • fileName specifiesthe name of the file that you want to open. • When you create an input stream, if the file does not exist, then FileNotFoundException is thrown. • For outputstreams, if the file cannot be opened or created, then FileNotFoundException is thrown. • FileNotFoundException is a subclass of IOException. When an output file is opened, any preexisting file by the same name is destroyed
  • 152.
    Close method • Whenyou are done with a file, you must close it. This is done by calling the close( ) method, which is implemented by both FileInputStream and FileOutputStream. • It is shown here: • void close( ) throws IOException • Closing a file releases the system resources allocated to the file, allowing them to be used byanother file. Failure to close a file can result in “memory leaks” because of unused resources remaining allocated.
  • 153.
    Read method • Toread from a file, you can use a version of read( ) that is defined within FileInputStream. The one that we will use is shown here: • int read( ) throws IOException • Each time that it is called, it reads a single byte from the file and returns the byte as an integer value. read( ) returns –1 when the end of the file is encountered. It can throw an IOException.
  • 154.
    • The followingprogram uses read( ) to input and display the contents of a file that • contains ASCII text. The name of the file is specified as a command-line argument. /* Display a text file. To use this program, specify the name of the file that you want to see. For example, to see a file called TEST.TXT, use the following command line. • java ShowFile TEST.TXT */
  • 155.
    To open andread a file import java.io.*; class ShowFile { public static void main(String args[]) { int i; FileInputStream fin; // First, confirm that a filename has been specified. if(args.length != 1) { System.out.println("Usage: ShowFile filename"); return; } // Attempt to open the file. try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("Cannot Open File"); return; } // At this point, the file is open and can be read. // The following reads characters until EOF is encountered.
  • 156.
    Cont…. try { do { i= fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); } catch(IOException e) { System.out.println("Error Reading File"); } // Close the file. try { fin.close(); } catch(IOException e) { System.out.println("Error Closing File"); } } }
  • 157.
    Finally block • Thevariation is to call close( ) within a finally block. • In this approach, all of the methods that access the file are contained within a try block, and the finally block is used to close the file. This way, no matter how the try block terminates,the file is closed. Assuming the preceding example, here is how the try block that reads the • file can be recoded:
  • 158.
    finally try { do { i= fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); } catch(IOException e) { System.out.println("Error Reading File"); } finally { // Close file on the way out of the try block. try { fin.close(); } catch(IOException e) { System.out.println("Error Closing File"); } }
  • 159.
    • Although notan issue in this case, one advantage to this approach in general is that if the code that accesses a file terminates because of some non-I/O related exception, the file is still closed by the finally block. • Sometimes it’s easier to wrap the portions of a program that open the file and access • the file within a single try block (rather than separating the two) and then use a finally block to close the file.
  • 160.
    • /* Displaya text file. To use this program, specify the name of the file that you want to see. For example, to see a file called TEST.TXT, use the following command line. java ShowFile TEST.TXT This variation wraps the code that opens and accesses the file within a single try block. The file is closed by the finally block. */
  • 161.
    import java.io.*; class ShowFile{ public static void main(String args[]) { int i; FileInputStream fin = null; // First, confirm that a filename has been specified. if(args.length != 1) { System.out.println("Usage: ShowFile filename"); return; } // The following code opens a file, reads characters until EOF // is encountered, and then closes the file via a finally block. try { fin = new FileInputStream(args[0]); do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); } catch(FileNotFoundException e) { System.out.println("File Not Found."); }
  • 162.
    catch(IOException e) { System.out.println("AnI/O Error Occurred"); } finally { // Close file in all cases. try { if(fin != null) fin.close(); } catch(IOException e) { System.out.println("Error Closing File"); } } } }
  • 163.
    Write method • Towrite to a file, you can use the write( ) method defined by FileOutputStream. Its • simplest form is shown here: void write(int byteval) throws IOException • This method writes the byte specified by byteval to the file. Although byteval is declared as an integer, only the low-order eight bits are written to the file. If an error occurs during writing, an IOException is thrown. The next example uses write( ) to copy a file:
  • 164.
    Copy a file •/* Copy a file. • To use this program, specify the name • of the source file and the destination file. • For example, to copy a file called FIRST.TXT • to a file called SECOND.TXT, use the following • command line. • java CopyFile FIRST.TXT SECOND.TXT • */
  • 165.
    example • import java.io.*; •class CopyFile { • public static void main(String args[]) throws IOException • { • int i; • FileInputStream fin = null; • FileOutputStream fout = null; • // First, confirm that both files have been specified. • if(args.length != 2) { • System.out.println("Usage: CopyFile from to"); • return;
  • 166.
    • } // Copya File. try { // Attempt to open the files. fin = new FileInputStream(args[0]); fout = new FileOutputStream(args[1]); do { i = fin.read(); if(i != -1) fout.write(i); } while(i != -1); } catch(IOException e) { System.out.println("I/O Error: " + e); } finally { try { if(fin != null) fin.close(); } catch(IOException e2) { System.out.println("Error Closing Input File"); } try { if(fout != null) fout.close(); } catch(IOException e2) { System.out.println("Error Closing Output File"); } } }} • In the program, notice that two separate try blocks are used when closing the files. This • ensures that both files are closed, even if the call to fin.close( ) throws an exception.
  • 167.
    Automatically Closing aFile • Here is its general form: try (resource-specification) { // use the resource } • Here, resource-specification is a statement that declares and initializes a resource, such as a file stream. It consists of a variable declaration in which the variable is initialized with a reference to the object being managed. When the try block ends, the resource is automatically released. • In the case of a file, this means that the file is automatically closed. (Thus, there is no need to call close( ) explicitly.) Of course, this form of try can also include catch and finally clauses. • This new form of try is called the try-with-resources statement.
  • 168.
    /* This versionof the ShowFile program uses a try-with-resources statement to automatically close a file after it is no longer needed. Note: This code requires JDK 7 or later. */ import java.io.*; class ShowFile { public static void main(String args[]) { int i; // First, confirm that a filename has been specified. if(args.length != 1) { System.out.println("Usage: ShowFile filename"); return; } // The following code uses a try-with-resources statement to open // a file and then automatically close it when the try block is left. try(FileInputStream fin = new FileInputStream(args[0])) { do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); } catch(FileNotFoundException e) { System.out.println("File Not Found."); } catch(IOException e) { System.out.println("An I/O Error Occurred"); } }
  • 169.
    Copy • /* Aversion of CopyFile that uses try-with-resources. • It demonstrates two resources (in this case files) being • managed by a single try statement. • */ • import java.io.*; • class CopyFile { • public static void main(String args[]) throws IOException • { • int i; • // First, confirm that both files have been specified. • if(args.length != 2) { • System.out.println("Usage: CopyFile from to"); • return; • } • // Open and manage two files via the try statement. • try (FileInputStream fin = new FileInputStream(args[0]); • FileOutputStream fout = new FileOutputStream(args[1])) • { • do { • i = fin.read(); • if(i != -1) fout.write(i); • } while(i != -1); • 318 PART I The Java Language • } catch(IOException e) { • System.out.println("I/O Error: " + e); • } • } • } • In this program, notice how the input and output files are opened within the try block: • try (FileInputStream fin = new FileInputStream(args[0]); • FileOutputStream fout = new FileOutputStream(args[1])) • { • // ... • After this try block ends, both fin and fout will have been closed. If you compare this • version of the program to the previous version, you will see that it is much shorter. The • ability to streamline source code is a side-benefit of automatic resource management.
  • 170.
    API nio(newIO) • Java2, version 1.4 added a new way to handle I/O operations. Called the new I/O APIs, it is one of the more interesting additions that Sun included in the 1.4 release because it supports a channel-based approach to I/O operations. The new I/O classes are contained in the five packages shown here. • Package Purpose • java.nio --------------------Top-level package for the new I/O system. Encapsulates various types of buffers which contain data operated upon by the new I/O system. • java.nio.channels -------------Supports channels, which are essentially open I/O connections. • java.nio.channels.spi -----------Supports service providers for channels. • java.nio.charset --------------------Encapsulates character sets. Also supports encoders and decoders that convert characters to bytes and bytes to characters, respectively. • java.nio.charset.spi --------------Supports service providers for character sets. • NIO classes supplement the standard I/O system, giving you an alternative approach, which can be beneficial in some circumstances.
  • 171.
    NIO FUNDAMENTALS • Thenew I/O system is built on two foundational items: buffers and channels. • A buffer holds data. • A channel represents an open connection to an I/O device, such as a file or a socket.
  • 172.
    BUFFERS • Buffers • Buffersare defined in the java.nio package. All buffers are subclasses of the Bufferclass, which defines the core functionality common to all buffers: current position,limit, and capacity. • The current position is the index within the buffer at which the next read or write operation will take place. The current position is advanced by most read or write operations. • The limit is the index of the end of the buffer. • The capacity is the number of elements that the buffer can hold.
  • 173.
    BUFFER METHODS • finalint capacity( ) ------Returns the number of elements that the invoking buffer is capable of holding. • final Buffer clear( ) -------Clears the invoking buffer and returns a reference to the buffer. • final Buffer flip( ) ----------Sets the invoking buffer’s limit to the currentposition and resets the current position to 0. • Returns a reference to the buffer. • final boolean hasRemaining( ) --------------Returns true if there are elements remaining in the invoking buffer. Returns false otherwise. • abstract boolean isReadOnly( ) ------------------Returns true if the invoking buffer is read- only. Returns false otherwise. • final int limit( ) --------------------Returns the invoking buffer’s limit. • final Buffer limit(int n) -----------------------Sets the invoking buffer’s limit to n. Returns a reference to the buffer. • final Buffer mark( ) -------------------Sets the mark and returns a reference to the invoking buffer. • final int position( ) ----------------------------Returns the current position. • final Buffer position(int n) ------------------------Sets the invoking buffer’s current position to n. Returns a reference to the buffer. • final Buffer reset( ) -----------------Resets the current position of the invoking buffer to the previously set mark. Returns a reference to the buffer. • final Buffer rewind( ) --------------Sets the position of the invoking buffer to 0. Returns a reference to the buffer.
  • 174.
    BUFFER CLASSES • FromBuffer are derived the following specific buffer classes, which hold the type • of data that their names imply. • ByteBuffer • CharBuffer • DoubleBuffer • FloatBuffer • IntBuffer • LongBuffer • MappedByteBuffer • ShortBuffer • MappedByteBuffer is a subclass of ByteBuffer that is used to map a file to a buffer. • All buffers support various get( ) and put( ) methods, which allow you to get data • from a buffer or put data into a buffer.
  • 175.
    BYTE BUFFER METHODS •METHOD: • abstract byte get( ) ------Returns the byte at the current position. • ByteBuffer get(byte vals[ ] )---- Copies the invoking buffer into the array referred to by vals. Returns a reference to the buffer. • final ByteBuffer put(byte vals[ ] ) -----Copies all elements of vals into the invoking buffer, beginning at the currentposition. Returns a reference to the buffer.
  • 176.
    CHANNELS • Channels aredefined in java.nio.channels. A channel represents an open connection to an • I/O source or destination. You obtain a channel by calling getChannel( ) on an object that supports channels.
  • 177.
    Channel classes getChannel( )to the following I/O classes. FileInputStream FileOutputStream RandomAccessFile socket ServerSocket DatagramSocket • Thus, to obtain a channel, you first obtain an object of one of these classes and then call getChannel( ) on that object. The specific type of channel returned depends upon the type of object getChannel( ) is called on. For example, when called on a FileInputStream, FileOuputStream, or RandomAccessFile, getChannel( ) returns a channel of type FileChannel. When calledon a Socket, getChannel( ) returns a SocketChannel. Channels such as FileChannel and SocketChannel support various read( ) and • write( ) methods that enable you to perform I/O operations through the channel. Forexample, here are a few of the read( ) and write( ) methods defined for FileChannel
  • 178.
    Channel methods • abstractint read(ByteBuffer bb) Reads bytes from the invoking channel into bbuntil the buffer is full, or there is no more input.Returns the number of bytes actually read. • abstract int write(ByteBuffer bb) Writes the contents of bb to the invoking channel, starting at the current position. Returns the number of bytes written.
  • 179.
    Charset and selectors •Charsets and Selectors • Two other entities used by NIO are charsets and selectors. • A charset defines the way that bytes are mapped to characters. You can encode a sequence of characters into bytes using an encoder. You can decode a sequence of bytes into characters using a decoder. Charsets, encoders, and decoders are supported by classes defined in the • java.nio.charset package. Because default encoders and decoders are provided, you will not often need to work explicitly with charsets. • A selector supports key-based, non-blocking, multiplexed I/O. In other words, selectors enable you to perform I/O through multiple channels. Selectors are supported by classes defined in the java.nio.channels package. Selectors are most applicable to socket-backed channels.
  • 180.
    Reading a File •read a file using a channel and a manually allocated buffer, follow this procedure. • First open the file for input using FileInputStream. Then, obtain a channel to this file by calling getChannel( ). It has this general form: • FileChannel getChannel( ) It returns a FileChannel object, which encapsulates the channel for file operations. Once • a file channel has been opened, obtain the size of the file by calling size( ), shown here: long size( ) throws IOException • It returns the current size, in bytes, of the channel, which reflects the underlying file. • Next, call allocate( ) to allocate a buffer large enough to hold the file’s contents. Because file channels operate on byte buffers you will use the allocate( ) method defined by ByteBuffer. • It has this general form. • static ByteBuffer allocate(int cap)
  • 181.
    Reading a file importjava.io.*; import java.nio.*; import java.nio.channels.*; public class ExplicitChannelRead { public static void main(String args[]) FileInputStream fIn; FileChannel fChan; long fSize; ByteBuffer mBuf; try // First, open a file for input. fIn = new FileInputStream("test.txt"); // Next, obtain a channel to that file. fChan = fIn.getChannel(); // Now, get the file's size. fSize = fChan.size(); // Allocate a buffer of the necessary size. mBuf = ByteBuffer.allocate((int)fSize); // Read the file into the buffer. fChan.read(mBuf); // Rewind the buffer so that it can be read. mBuf.rewind(); // Read bytes from the buffer. for(int i=0; i < fSize; i++) System.out.print((char)mBuf.get()); System.out.println(); fChan.close(); // close channel fIn.close(); // close file } catch (IOException exc) { System.out.println(exc); System.exit(1); } } }
  • 182.
    Map method • Themap( ) method is shown here: • MappedByteBuffer map(FileChannel.MapMode how,long pos, long size) throws IOException • The map( ) method causes the data in the file to be mapped into a buffer in memory. • The value in how determines what type of operations are allowed. It must be one of these values. • MapMode.READ • MapMode.READ_WRITE • MapMode.PRIVATE
  • 183.
    Using map toread a file • The following program reworks the first example so that it uses a mapped file. // Use a mapped file to read a text file. import java.io.*; import java.nio.*; import java.nio.channels.*; public class MappedChannelRead { public static void main(String args[]) { FileInputStream fIn; FileChannel fChan; long fSize; MappedByteBuffer mBuf; try { // First, open an file for input. fIn = new FileInputStream("test.txt"); // Next, obtain a channel to that file. fChan = fIn.getChannel(); // Get the size of the file. fSize = fChan.size(); // Now, map the file into a buffer. mBuf = fChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); // Read bytes from the buffer. for(int i=0; i < fSize; i++) System.out.print((char)mBuf.get()); fChan.close(); // close channel fIn.close(); // close file } catch (IOException exc) { System.out.println(exc); System.exit(1); } } }
  • 184.
    Writing to aFile • There are several ways to write to a file through a channel. Again, we will look at two. First, you can write data to an output file through a channel, by using explicit write operations. • Second, if the file is opened for read/write operations, you can map the file to a buffer and then write to that buffer. Changes to the buffer will automatically be reflected in the file. Both ways are described here. • To write to a file through a channel using explicit calls to write( ), follow these steps. First, open the file for output. Then, allocate a byte buffer, put the data you want to write into that buffer, and then called write( ) on the channel. • The following program demonstrates this procedure. It writes the alphabet to a file called test.txt.
  • 185.
    // Write toa file using the new I/O. import java.io.*; import java.nio.*; import java.nio.channels.*; public class ExplicitChannelWrite { public static void main(String args[]) { FileOutputStream fOut; FileChannel fChan; ByteBuffer mBuf; try { fOut = new FileOutputStream("test.txt"); // Get a channel to the output file. fChan = fOut.getChannel(); // Create a buffer. mBuf = ByteBuffer.allocateDirect(26); // Write some bytes to the buffer. for(int i=0; i<26; i++) mBuf.put((byte)('A' + i)); // Rewind the buffer so that it can written. mBuf.rewind(); // Write the buffer to the output file. fChan.write(mBuf); // close channel and file. fChan.close(); fOut.close(); } catch (IOException exc) { System.out.println(exc); System.exit(1); } } }
  • 186.
    Map method forwrite • To write to a file using a mapped file, follow these steps. First, open the file for • read/write operations. Next, map that file to a buffer by calling map( ). Then, write to the buffer. Because the buffer is mapped to the file, any changes to that buffer are automatically reflected in the file. • Thus, no explicit write operations to the channel are necessary. Here is the preceding program reworked so that a mapped file is used.
  • 187.
    Map method // Writeto a mapped file. import java.io.*; import java.nio.*; import java.nio.channels.*; public class MappedChannelWrite { 856 J a v a ™ 2 : T h e C o m p l e t e R e f e r e n c e public static void main(String args[]) { RandomAccessFile fOut; FileChannel fChan; ByteBuffer mBuf; try { fOut = new RandomAccessFile("test.txt", "rw"); // Next, obtain a channel to that file. fChan = fOut.getChannel(); // Then, map the file into a buffer. mBuf = fChan.map(FileChannel.MapMode.READ_WRITE, 0, 26); // Write some bytes to the buffer. for(int i=0; i<26; i++) mBuf.put((byte)('A' + i)); // close channel and file. fChan.close(); fOut.close(); } catch (IOException exc) { System.out.println(exc); System.exit(1); }
  • 188.
    Copying a FileUsing the New I/O • The new I/O system simplifies some types of file operations. For example, the following program copies a file. It does so by opening an input channel to the source file and an output channel to the target file. It then writes the mapped input buffer to the output file in a single operation.
  • 189.
    Copy import java.io.*; import java.nio.*; importjava.nio.channels.*; public class NIOCopy { public static void main(String args[]) { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; try { fIn = new FileInputStream(args[0]); fOut = new FileOutputStream(args[1]); // Get channels to the input and output files. fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); // Get the size of the file. fSize = fIChan.size(); // Map the input file to a buffer. mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);
  • 190.
    copy // Write thebuffer to the output file. fOChan.write(mBuf); // this copies the file // Close the channels and files. fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } catch (IOException exc) { System.out.println(exc); System.exit(1); } catch (ArrayIndexOutOfBoundsException exc) { System.out.println("Usage: Copy from to"); 858 J a v a ™ 2 : T h e C o m p l e t e R e f e r e n c e System.exit(1); } } }