OOPS THROUGH JAVA R19 UNIT-4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

OBJECT ORIENTED PROGRAMMING

THROUGH JAVA

(R-20 regulation-ECE Department)

I YEAR – II SEMISTER

UNIT-4

Prepared by

P DEVI SRIDURGA,

Assistant Professor, CSE Department,


SIET.
OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Unit-4

IO Programming in Java

Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of a stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.

I/O Streams:
• A Stream is linked to a physical layer by java I/O system to make input and output
operation in java.
• In general, a stream means continuous flow of data.
• An I/O Stream represents an input source or an output destination.
• A stream can represent many different kinds of sources and destinations, including disk
files, devices, other programs, and memory arrays.
• Streams support many different kinds of data, including simple bytes, primitive data
types, localized characters, and objects.
• Some streams simply pass on data; others manipulate and transform the data in useful
ways.

A stream is a sequence of data. A program uses an input stream to read data from a
source, one item at a time:

Reading information into a program.

A program uses an output stream to write data to a destination, one item at time:

Writing information from a program.


In Java, 3 streams are created for us automatically. All these streams are attached with the
console.

1) System.out: standard output stream 2) System.in: standard input stream

3) System.err: standard error stream

Java encapsulates Stream under java.io package. Java defines two types of streams. They are,

1. Byte Stream: It provides a convenient means for handling input and output of byte.

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

Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream
and OutputStream.

Some important Byte stream classes.


Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method

InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.

Useful methods of InputStream


Method Description

1) read() reads the next byte of data from the input


returns -1 at the end of the file.

2)available() returns an estimate of the number of bytes that can be


read from the current input stream.

3) close() is used to close the current input stream

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream


Method Description

1) write(int) is used to write a byte to the current output

2) flush() flushes the current output stream.

3) close() is used to close the current output stream.

Two most important methods are


1. read() : reads byte of data.
2. write() : Writes byte of data.

FileInputStream Class

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader class.

Java FileInputStream class methods


Method Description

int It is used to return the estimated number of bytes that can be


available() read from the input stream.
int read() It is used to read the byte of data from the input stream.

void close() It is used to closes the stream.

Example:
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);

fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Note: Before running the code, a text file named as "testout.txt" is required to be created. In
this file, we are having following content: Welcome to java.

After executing the above program, you will get a single character from the file which is 87 (in
byte form). To see the text, you need to convert it into character.

Output:

FileOutputStream Class

Java FileOutputStream is an output stream used for writing data to a file.


FileOutputStream class methods
Method Description

void write(int b) It is used to write the specified byte to the file output stream.

void close() It is used to closes the file output stream.

Example:
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

Output:

Success...

The content of a text file testout.txt is set with the data A.

testout.txt

BufferedOutputStream Class

Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer
to store data.
BufferedOutputStream class methods
Method Description

void write(int b) It writes the specified byte to the buffered output stream.

void flush() It flushes the buffered output stream.

Example:
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[]){
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to java ";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}

Output:

Success

testout.txt

Welcome to java.

BufferedInputStream Class

Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
BufferedInputStream class methods

Method Description

int It returns an estimate number of bytes that can be read from the input stream without bloc
available() method for the input stream.

int read() It read the next byte of data from the input stream.

void close() It closes the input stream and releases any of the system resources associated with the stre

Example:
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Here, we are assuming that you have following data in "testout.txt" file:

java

Output:

java
DataOutputStream Class

Java DataOutputStream class allows an application to write primitive data types to the output
stream in a machine-independent way.

Java application generally uses the data output stream to write data that can later be read by a
data input stream.

DataOutputStream class methods

Method Description

int size() It is used to return the number of bytes written to the


data output stream.

void write(int b) It is used to write the specified byte to the underlying output stream.

void writeBoolean(boolean It is used to write Boolean to the output stream as a 1-byte value.
v)

void writeChar(int v) It is used to write char to the output stream as a 2-byte value.

void writeChars(String s) It is used to write string to the output stream as a sequence of characters.

void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.

void writeInt(int v) It is used to write an int to the output stream

void writeShort(int v) It is used to write a short to the output stream.

void writeShort(int v) It is used to write a short to the output stream.

void writeLong(long v) It is used to write a long to the output stream.


void flush() It is used to flushes the data output stream.

Example:
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}

Output:

Succcess...

testout.txt:

DataInputStream Class

Java DataInputStream class allows an application to read primitive data from the input stream in
a machine-independent way.

DataInputStream class Methods


Method Description

int read(byte[] b) It is used to read the number of bytes from the input stream.
int readInt() It is used to read input bytes and return an int value.

byte readByte() It is used to read and return the one input byte.

char readChar() It is used to read two input bytes and returns a char value.

double readDouble() It is used to read eight input bytes and returns a double value.

boolean readBoolean() It is used to read one input byte and return true if byte is non zero, false if

Example:
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}

Here, we are assuming that you have following data in "testout.txt" file:

JAVA

Output:

J-A-V-A
Character Stream Classes
Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer. These two abstract classes have several concrete classes that handle unicode
character.
Some important Charcter stream classes.
Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamWriter Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output

BufferedReader Class

Java BufferedReader class is used to read the text from a character-based input stream. It can be
used to read data line by line by readLine() method. It inherits Reader class.

BufferedReader class methods


Method Description

int read() It is used for reading a single character.

String readLine() It is used for reading a line of text.

void close() It closes the input stream.

Example:
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);

int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}

Here, we are assuming that you have following data in "testout.txt" file:

Welcome to java.

Output:

Welcome to java.

Reading Console Input

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

Reading input from keyboard in command window:


Output:

Explanation:
a) System.in object is predefined object of InputStream class, and it can read the keyboard input
as binary data.
b) InputStreamReader object converts the binary data into character data.
c) Buffered Reader object stores character data in a buffered memory, and converts into a string
object.
d) Interger.parseInt() methods converts the string data into numerical data.

BufferedWriter Class

Java BufferedWriter class is used to provide buffering for Writer instances

BufferedWriter Class methods


Method Description

void write(c) It is used to write a single character.

void flush() It is used to flushes the input stream.


void close() It is used to closes the input stream

Example:
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to java.");
buffer.close();
System.out.println("Success");
}
}

Output:

success

testout.txt:

Welcome to java.

java.io.File class:
• The java.io.File class object refers to a reference object to an actual physical file in the
memory. ( like a FILE pointer in C language)
• This class is used to know the properties of a file like
– path of the file,
– whether the file exists or not,
– whether the file is a file or a directory,
– length of the file, etc.
java.io.File class methods:
 File Constructors
o public File(String path)
o public File(String path, String name)
o public File(File dir, String name)
 File Methods
o public String getName()
o public String getPath()
o public String getAbsolutePath()
o public String getParent()
o public boolean exists() throws SecurityException
o public booleancanWrite() throws SecurityException
o public booleancanRead() throws SecurityException
o public booleanisFile() throws SecurityException
o public booleanisDirectory() throws SecurityException
o public booleanisAbsolute()
o public long lastModified() throws SecurityException
o public long length() throws SecurityException
o public booleanmkdir()
o public booleanmkdirs() throws SecurityException
o public booleanrenameTo(File destination) throws SecurityException
o public boolean delete() throws SecurityException

Example:
Output:

Reading Content from the file:

import java.io.*;
classReadFileDemo{
public static void main(String args[]) throws Exception
{
File f1=new File(args[0]);
byte[] b={};
if(f1.exists()){
FileInputStreamfis=new FileInputStream(f1);
b=new byte[fis.available()];
fis.read(b);
String s=new String(b);
System.out.println("Contents of "+args[0]+ ": \n"+ s);
fis.close();
}else{
System.out.println("File does not exist");
}
}
}
Output:

Writing Content to the file:


import java.io.*;
classWriteFileDemo{
public static void main(String args[]) throws Exception
{
FileOutputStreamfos=new FileOutputStream(args[0]);
System.out.println("File Opened, now writing contents");
String str = "Welcome to java programming." +
"\nThis is example for File operations.";
byte[] b = str.getBytes();
fos.write(b);
fos.flush();
System.out.println("contents written");
System.out.println("Closing File");
fos.close();
}
}

Output:

Copy the content of one file into another file:

import java.io.*;
public class CopyFile{
public static void main(String[] args) throws Exception
{
int i;
FileInputStream fin = new FileInputStream(args[0]);
FileOutputStreamfout = new FileOutputStream(args[1]);
do {
i = fin.read();
if(i != -1) fout.write(i);
}while (i != -1);
fin.close();
fout.close();
}
}

Output:

RandomAccessFile
• The RandomAccessFile class provides a way to read from and write to a file in a
nonsequential manner.
• The constructor ofRandomAccessFile class has two arguments. The first argument
specifies the file to open, either as a String or a File object.
• The second argument is a String that must be either "r" or "rw". If the second argument is
"r", the file is opened for reading only. If the argument is "rw", however, the file is
opened for both reading and writing.

RandomAccessFileDemo.java

import java.io.*;
classRandomAccessFileDemo {
public static void main(String args[]) throws Exception
{
RandomAccessFileraf = new RandomAccessFile(args[0], "rw");
raf.seek(10);
byte b1[] = new byte[15];
raf.read(b1);
System.out.println("Read from file : " + new String(b1));
raf.seek(raf.length());
String s1 = "This is end of the file.”;
byte[] b2 = s1.getBytes();
raf.write(b2);
raf.close();
}
}
Output:

The content in the file before file operations: sample.txt


Welcome to java programming.
This is example for File operations.

The content in the file after file operations: sample.txt


Welcome to java programming.
This is example for File operations. This is end of the file.

Event Delegation Model of AWT

1) The event model is based on the Event Source and Event Listeners.
2) Event Listener is an object that receives the messages / events.
3) The Event Source is any object which creates the message / event.
4) The Event Delegation model is based on – The Event Classes, The Event Listeners, Event
Objects.
Steps involving in GUI Programming:
• Create object of container
• Set the layout of the container
• Add the objects of components to the container
• Override the event handler methods of event listeners against the action of the users
• Register the appropriate listener object with the components
Mechanism involved in Event Handling:
• Event Delegation model is based on the concept of an 'Event Source' and 'Event Listeners'.
• Any object that generates events due to user interaction is called an Event Source
• Ex : Button, Textbox, list,
• Any object that is interested in receiving messages (or events ) is called an Event Listener.
• Ex: ActionEvent, KeyEvent, MouseEvent etc.,
• We write the reaction for the action of user, by overriding the method of EventListener
( called Event Handler methods).
• Now the Event source registers with Event Listener.
• Event source generates corresponding Event Object due to user’s action on the Event source
component.
• The Event object generated by Event source is received by Event listener which is registered
with the Event source earlier.
• Now Event Listener executes the Event handler as the reaction against the action by the user.

Events – Event Sources – EventListeners:

ActionEvent:
•This event is generated by a component (such as a Button) when the component-specific
action occurs (such as click).
•The event is passed to an ActionListener object which is registered to receive the event
notification using the component’s addActionListener method.
•The event handler method is actionPerformed(), will be executed as event handler.
Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="EventDemo.class" width="400" height="150">
</applet>
*/
public class EventDemo extends Applet
{
public void init()
{
// setting layout to the container.
setLayout(new FlowLayout());
// creating component.
Button b1 = new Button("Change Color");
// adding component to the container.
add(b1);
// registering listener to component.
b1.addActionListener(new MyListener());
}
}
class MyListener implements ActionListener
{
// overriding event handler method
public void actionPerformed(ActionEvent ae)
{
// creating random color
int r = (int)(Math.random()*255);
int g = (int)(Math.random()*255);
int b = (int)(Math.random()*255);
// applying random color to background of container
Component cp =(Component) ae.getSource();
Container cn = (Container) cp.getParent();
cn.setBackground(new Color(r,g,b));
}
}
Output:

KeyEvent :
• KeyEvent is an event which indicates that a keystroke occurred in a component.
– public class KeyEvent extends InputEvent
• is generated by component object (such as a text field, Applet, Frame) when a key is
pressed, released, or typed.
• The event is passed to a KeyListener object which is registered to receive the event
notification using the component’s addKeyListener method.

Program:
KeyEventsDemo.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEventsDemo.class" width="400" height="200">
</applet>
*/
public class KeyEventsDemo extends Applet implements KeyListener
{
TextField t1;
int key;
String msg = "";
public void init() {
Label lname = new Label( "Enter some text : ");
t1 = new TextField(12);
add(lname);
add(t1);
t1.addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
key = ke.getKeyCode();
msg = "Key Down : " + (char) key;
repaint();
}
public void keyReleased(KeyEvent ke) {
key = ke.getKeyCode();
msg = "Key Up : " + (char)key;
repaint();
}
public void keyTyped(KeyEvent ke) {}
public void paint(Graphics g) {
showStatus(msg);
}
}
Output:

MouseEvent :
• It is an event which indicates that a mouse action occurred in a component.
• A mouse action occurs in a particular component if and only if the mouse cursor is over
the defined part of the component’s bounds when the action happens.
– public class MouseEvent extends InputEvent
• There are eight types of mouse events defined in the MouseEvent class.
Methods in the class MouseEvent:
int getButton()
Returns which, if any, of the mouse buttons has changed state.
int getClickCount()
Returns the number of mouse clicks associated with this event.
static String getMouseModifiersText(int modifiers)
Returns the modifier keys and mouse buttons, during the event, such as "Shift", or
"Ctrl+Shift".
int getX()
Returns the horizontal x position of the event relative to the source component.
int getY()
Returns the vertical y position of the event relative to the source component.

Program:
MouseMotionDemo.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseMotionDemo.class" width="300" height="200">
</applet>
*/
public class MouseMotionDemo extends Applet implements MouseMotionListener
{
int mx = 0,my = 0;
public void init() {
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent me) {
mx = me.getX();
my = me.getY();
repaint();
}
public void mouseMoved(MouseEvent me) {
mx = me.getX();
my = me.getY();
repaint();
}
public void paint(Graphics g) {
g.drawString( "*(" + mx + ", " + my + ")",mx,my);
}
}
Output:

Program to demonstrate MouseListener and MouseMotionListener:


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents.class" width="300" height="200">
</applet>
*/
public class MouseEvents extends Applet implements MouseListener,MouseMotionListener
{
String msg = "";
int mouseX = 0,mouseY = 0;
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me) {
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
public void mouseExited(MouseEvent me){
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mouseEntered(MouseEvent me){
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
public void mousePressed(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
public void mouseReleased(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "up";
repaint();
}
public void mouseDragged(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me) {
showStatus("Moving mouse at " + me.getX() + "," + me.getY());
}
public void paint(Graphics g) {
g.drawString(msg,mouseX,mouseY);
}
}
AdjustmentEvent :

•The adjustment events are generated by Adjustable objects like scroll bar.
Methods of AdjustmentEvent :
Program to demonstrate Adjustment event with scrollbar control:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SBDemo.class" width="300" height="200">
</applet>
*/
public class SBDemo extends Applet
implements AdjustmentListener{
String msg = "";
Scrollbar hsb;
public void init() {
hsb = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,200);
add(hsb);
hsb.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
public void paint(Graphics g) {
int r = hsb.getValue();
msg = "Horizontal: " + r;
g.drawString(msg,6,160);
g.drawOval(130,100,r,r);
}
}

Output:
FocusEvent :

•This event is generated when a component gains or loses focus.


•There are two types of focus events: permanent and temporary.
– Permanent focus event occurs when the user explicitly changes focus from one
component to other, e.g. by pressing tab key.
– Temporary focus event occurs when the focus is lost due to operations like
Window deactivated. In this case, when the window will again be activated, the
focus will be on same component.

Program to demonstrate focus event with button control:


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="FocusEventDemo.class" width="400" height="150">
</applet>
*/
public class FocusEventDemo extends Applet implements FocusListener
{
public void init()
{
Button b1 = new Button("Button 1");
add(b1);
b1.addFocusListener(this);
Button b2 = new Button("Button 2");
add(b2);
}
public void focusLost(FocusEvent fe)
{
showStatus("Button lost focus");
}
public void focusGained(FocusEvent fe)
{
showStatus("Button got focus");
}
}
Output:

ItemEvent :
•It is an event which shows whether an item was selected or de-selected.
– public class ItemEvent extends AWTEvent
•This event is generated by an ItemSelectable object (such as a List), where the event is
generated when an item of the list is either selected or de-selected.
•The event generated is passed to every ItemListener object which is registered to receive
such events.
•The method addItemListener() is used for this registration process.
Program to demonstrate ItemEvent with Checkbox control:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="ItemEventDemo" width="300" height="200">
</applet>
*/
public class ItemEventDemo extends Applet implements ItemListener
{
public void init() {
setLayout(new FlowLayout());
CheckboxGroup cp = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Large",cp,true);
Checkbox cb2 = new Checkbox("Medium",cp,false);
Checkbox cb3 = new Checkbox("Small",cp,false);
add(cb1);
add(cb2);
add(cb3);
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
showStatus(ie.getItem() + " got selected!");
}
}
Output:

TextEvent :
•This event indicates the change in the object’s text.
– public class TextEvent extends AWTEvent
•This event is generated by an object (such as a TextComponent) whenever its text changes.
The event is passed to every TextListener object which is registered to receive such
events.
The method addTextListener() is used for this registration process.

Program to demonstrate text event with a text field:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="TextEventDemo.class" width="400" height="150">
</applet>
*/
public class TextEventDemo extends Applet implements TextListener
{
public void init()
{
add(new Label("Enter some text : "));
TextField t1 = new TextField(15);
t1.addTextListener(this);
add(t1);
}
public void textValueChanged(TextEvent ae)
{
TextField t = (TextField)ae.getSource();
showStatus("You typed: " + t.getText());
}
}
Output:

You might also like