IT Unit 7 - Understand IO Streams and Applets in Java
IT Unit 7 - Understand IO Streams and Applets in Java
Applets in Java
By,
Asmatullah Khan,
CL/CP, GIOE,
Secunderabad.
Contents
1. Explain the concept of streams.
2. Explain various stream classes.
3. Describe the Basics of Applets – Life cycle of an applet.
4. Describe Applet classes, Applet Architecture.
5. Describe Applet Selection.
6. Explain the order of Applet initialization and termination.
7. Write a simple example for creating Applets.
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 A program uses an output stream to write data to a
source, one item at a time. destination, one item at time
Java I/O Operations – java.io Package
• Java IO package mostly concerns itself with the reading of raw data
from a source and writing of raw data to a destination.
• The InputStream and OutputStream classes in java.io are the abstract super classes that
define the behavior for sequential input and output streams in Java.
• Also included in java.io are several InputStream and OutputStream subclasses that
implement specific types of input and output streams.
• In java, 3 streams are created for us automatically. All these streams are attached with
console.
1. System.out: standard output stream
2. System.in: standard input stream
3. System.err: standard error stream
System.out.println("simple message");
System.err.println("error message");
Data -
PrintStream PrintWriter
Formatted
Objects ObjectInputStream ObjectOutputStream
SequenceInputStream
Utilities
Byte Streams
• Java byte streams are
used to perform input
and output of 8-bit
bytes.
• An output stream accepts output bytes and sends them to some sink (buffer).
Commonly used methods of OutputStream class
Method Description
bout.flush();
bout.close();//has no effect
System.out.println("success...");
}
}
import java.io.*;
import java.util.*;
class B{
class
FileInputStream fin2=new FileInputStream("abc2.txt");
FileInputStream fin3=new FileInputStream("abc.txt");
FileInputStream fin4=new FileInputStream("B.java");
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
fin2.close(); }}
Java BufferedOutputStream and BufferedInputStream
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Example of Java BufferedInputStream
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.println((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Reading data from keyboard
• There are many ways to read data from the keyboard. For example:
1. InputStreamReader
2. Console
3. Scanner
4. DataInputStream etc.
1. InputStreamReader class
▫ InputStreamReader class can be used to read data from keyboard.
▫ It performs two tasks:
connects to input stream of keyboard
converts the byte-oriented stream into character-oriented stream
• BufferedReader class
▫ BufferedReader class can be used to read data line by line by readLine() method.
Example of reading data from keyboard by
InputStreamReader and BufferdReader class
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
• If you read password using Console class, it will not be displayed to the user.
• The java.io.Console class is attached with system console internally. The Console
class is introduced since Java 1.5.
import java.io.*;
import java.io.*; class ReadPasswordTest{
class ReadStringTest{ public static void main(String args[]){
public static void main(String args[]){ Console c=System.console();
Console c=System.console(); System.out.println("Enter password: ");
System.out.println("Enter your name: "); char[] ch=c.readPassword();
//converting char array into string
String n=c.readLine(); String pass=String.valueOf(ch);
System.out.println("Welcome "+n); System.out.println("Password is: "+pass);
}
} }
}
Output: Output:
Enter your name: james gosling Enter password:
Welcome james gosling Password is: sonoo
Java Scanner class
• The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace by default.
• Java Scanner class is widely used to parse text for string and primitive types using
regular expression. Java Scanner class extends Object class and implements
Iterator and Closeable interfaces.
import java.util.Scanner;
Output:
class ScannerTest{ Enter your rollno
public static void main(String args[]){ 111
Scanner sc=new Scanner(System.in); Enter your name
Ratan
System.out.println("Enter your rollno"); Enter your fee
int rollno=sc.nextInt(); 450000
Rollno:111 name:Ratan fee:450000
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
java.io.PrintStream class
• The PrintStream class provides methods to write data to another stream.
• The PrintStream class automatically flushes the data so there is no need to call
flush() method.
import java.io.*;
class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("mfile.txt");
PrintStream pout=new PrintStream(fout);
pout.println(1900);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
}
}
An applet is a Java program that runs in a Web browser.
An applet can be a fully functional Java application because it has the entire
Java API at its disposal.
Applets are small Java applications that can be accessed on an Internet server,
transported over Internet, and can be automatically installed and run as apart
of a web document.
It is viewed using JVM. The JVM can use either a plug-in of the Web browser
or a separate runtime environment to run an applet application.
JVM creates an instance of the applet class and invokes init() method to
initialize an Applet.
Java Applet Execution Process
Advantages of Applet
1. As applet is a small java program, so it is platform independent code which is capable to
run on any browser.
2. Applets can perform various small tasks on client-side machines. They can play sounds,
show images, get user inputs, get mouse clicks and even get user keystrokes, etc ...
3. Applets creates and edit graphics on client-side which are different and independent of
client-side platform.
6. Applets are secure and safe to use because they cannot perform any modifications over
local system.
7. Various small tasks such as performing login, inventory checking, task scheduling can be
done by applets running over Intranets.
2. A main() method is not invoked on an applet, and an applet class will not
define main().
4. When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
5. A JVM is required to view an applet. The JVM can be either a plug-in of the
Web browser or a separate runtime environment.
6. The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
7. Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the
applet to a child playing in a sandbox with various rules that must be followed.
8. Other classes that the applet needs can be downloaded in a single Java Archive
(JAR) file.
Life Cycle of an Applet
• Various states, an applet, undergoes between its object creation and object removal (when
the job is over) is known as Applet Life Cycle.
• These methods are known as "callback methods" as they are called automatically by the
browser whenever required for the smooth execution of the applet.
▫ Programmer just write the methods with some code but never calls.
• These methods are defined in java.applet.Applet class except paint() method. The
paint() method is defined in java.awt.Component class, an indirect super class of Applet.
start():
• In init() method, even though applet object is created, it is
in inactive state.
• An inactive applet is not eligible for microprocessor time
even though the microprocessor is idle.
• To make the applet active, the init() method calls start()
method.
▫ In start() method, applet becomes active and thereby eligible for
processor time.
• start() method is called by the init() method. This method is
called a number of times in the life cycle; whenever the
applet is deiconifed , to make the applet active.
Description of Applet Life Cycle Methods
paint():
• This method takes a java.awt.Graphics object as parameter.
• This class includes many methods of drawing, necessary to draw on the
applet window.
• This is the place where the programmer can write his code of what
he expects from applet like animation etc.
• This is equivalent to runnable state of thread.
• paint() method is called by the start() method. This is called number of
times in the execution.
stop():
• In this method the applet becomes temporarily inactive.
• An applet can come any number of times into this method in its life cycle and
can go back to the active state (paint() method) whenever would like.
• It is the best place to have cleanup code.
• It is equivalent to the blocked state of the thread.
• stop() method is called whenever the applet window is iconified to
inactivate the applet. This method is called number of times in the execution.
destroy():
• This method is called just before an applet object is garbage collected.
• This is the end of the life cycle of applet.
• It is the best place to have cleanup code.
• It is equivalent to the dead state of the thread.
• destroy() method is called when the applet is closed. This method is called
only once in the life cycle.
Executing an Applet
1. Using HTML File 2. Using Appletviewer java Utility
//First.java //First.java
import java.applet.Applet; import java.applet.Applet;
import java.awt.Graphics; import java.awt.Graphics;
public class First extends Applet public class First extends Applet
{ {
public void paint(Graphics g){ public void paint(Graphics g){
g.drawString("welcome",150,150); g.drawString("welcome to applet",
} 150,150);
} }
}
//myapplet.html /*
<applet code="First.class" width="3
<html> 00" height="300">
<body> </applet>
<applet code="First.class" */
width="300" height="300">
</applet>
c:\>javac First.java
</body>
c:\>appletviewer First.java
</html>
Displaying Graphics in Applet – Graphics Class
1. public abstract void drawString(String str, int x, int y) is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height) draws a rectangle with the specified
width and height.
3. public abstract void fillRect(int x, int y, int width, int height) is used to fill rectangle with
the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height) is used to draw oval with
the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height) is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2) is used to draw line between the
points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer) is
used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) is
used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c) is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font) is used to set the graphics current font to the
specified font.
Graphics Class Usage Example
import java.applet.Applet;
import java.awt.*;