Professional Documents
Culture Documents
Unit 7 - Understand IO Streams and Applets in Java
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's IO package mostly concerns itself with the reading of raw
data from a source and writing of raw data to a destination.
• 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");
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
Java IO Class Overview
Value
Byte Based Character Based
Type
Input Output Input Output
Reader Writer
Basic InputStream OutputStream
InputStreamReader OutputStreamWriter
Arrays ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter
FileInputStream FileOutputStream
Files FileReader FileWriter
RandomAccessFile RandomAccessFile
Pipes PipedInputStream PipedOutputStream PipedReader PipedWriter
Buffering BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
Filtering FilterInputStream FilterOutputStream FilterReader FilterWriter
PushbackInputStream PushbackReader
Parsing
StreamTokenizer LineNumberReader
Strings StringReader StringWriter
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
//converting string into byte array
byte b[]=s.getBytes();
fout.write(b);
fout.close(); Output:
System.out.println("success...");
}catch(Exception e){system.out.println(e);} success...
}
}
Example of FileInputStream class
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}catch(Exception e){system.out.println(e);}
}
} Output:
Sachin is my favorite player.
Reading the data of current java file and
writing it into another file
import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");
int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}
Java ByteArrayOutputStream class
• Java ByteArrayOutputStream class is used to write data into multiple files. In this
stream, the data is written into a byte array that can be written to multiple stream.
Java public static void main(String args[])throws IOException{
//creating the FileInputStream objects for all the files
SequenceInputStream FileInputStream fin=new FileInputStream("A.java");
FileInputStream fin2=new FileInputStream("abc2.txt");
class FileInputStream fin3=new FileInputStream("abc.txt");
FileInputStream fin4=new FileInputStream("B.java");
//creating Vector object to all the stream
Vector v=new Vector();
• Java SequenceInputStream v.add(fin); v.add(fin2);
v.add(fin3); v.add(fin4);
class is used to read data
from multiple streams. //creating enumeration object by calling the elements method
Enumeration e=v.elements();
• It reads data of streams one
//passing the enumeration object in the constructor
by one.
SequenceInputStream bin=new SequenceInputStream(e);
int i=0;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
fin2.close(); }}
Java BufferedOutputStream and BufferedInputStream
• 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 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. It provides many methods to read and parse
various primitive values.
• 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.
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.
7. Applets tend to be slow on execution because all the classes and resources
which it needs have to be transported over the network.
Applet vs Standalone Java application
1. An applet is a Java class that extends the java.applet.Applet class.
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.
start():
• In init() method, even through 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
• Using HTML File • 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.*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50); <html>
g.drawLine(20,30,20,300); <body>
g.drawRect(70,100,30,30); <applet code="GraphicsDemo.class"
g.fillRect(170,100,30,30); width="300" height="300">
g.drawOval(70,200,30,30); </applet>
</body>
g.setColor(Color.pink); </html>
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
Java Applet Development Using Swings
Setting Font in Applet
Setting Color in Applet
Making Art in Applet
Invoking User defined Methods in Applets
Example of displaying image in applet
import java.awt.*; <html>
import java.applet.*; <body>
<applet code="DisplayImage.class"
public class DisplayImage extends Applet
width="300" height="300"> </applet
{ >
Image picture; </body>
public void init() { </html>
picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
• Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose image is required to be displayed.
The java.awt.Graphics class provide a method drawImage() to display the image.
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.
The java.applet.Applet class provides getImage() method that returns the object of Image.
public URL getDocumentBase(): is used to return the URL of the document in which applet is
embedded.
public URL getCodeBase(): is used to return the base URL.
Applet with GUI input Options cont…
Applet with GUI input Options cont…
Output of GUI input Applet
Pattern Formation Applet Example
import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet {
int width, height;
public void init()
{ width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void paint( Graphics g )
{
g.setColor( Color.green );
for ( int i = 0; i < 10; ++i )
{
g.drawLine( width, height, i * width / 10, 0 );
}
}
}
Events
• Events in Java are triggered when:
• User selects a button/checkbox/item in list/etc.
• User moves/drags the mouse
• User types a key
• Timer expires
• More…
• Each event automatically calls a particular method
to
• handle the type of event that occurred.
Event Handling in Applets
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){ <html>
tf=new TextField(); <body>
tf.setBounds(30,40,150,20); <applet code="EventApplet.class"
b=new Button("Click"); width="300" height="300">
b.setBounds(80,150,60,50); </applet>
add(b);add(tf); </body>
b.addActionListener(this); </html>
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}