Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Unit 7 - I/O streams and

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 most typical sources and destinations of data are these:


▫ Files
▫ Pipes
▫ Network Connections
▫ In-memory Buffers (e.g. arrays)
▫ System.in, System.out, System.error

• IO Streams are a core concept in Java IO.


▫ A stream is a conceptually endless flow of data.
▫ You can either read from a stream or write to a stream.
▫ A stream is connected to a data source or a data destination.

• Streams in Java IO can be either


▫ byte based (reading and writing bytes) or
▫ character based (reading and writing characters).
Java IO Purposes and Features
• File Access
• Network Access
• Internal Memory Buffer Access
• Inter-Thread Communication (Pipes)
• Buffering
• Filtering
• Parsing
• Reading and Writing Text (Readers / Writers)
• Reading and Writing Primitive Data (long, int etc.)
• Reading and Writing Objects
Support for i/o streams - java.io Classes
• The Java development environment includes a package, java.io, that contains a set of input
and output streams that java programs can use to read and write data.

• 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");

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 Type Byte Based Character Based

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 DataInputStream DataOutputStream

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.

• Though there are many


classes related to byte
streams but the most
frequently used classes
are, FileInputStream
and
FileOutputStream.
Character Streams
• Java Character streams are
used to perform input and
output for 16-bit unicode.

• Though there are many classes


related to character streams
but the most frequently used
classes are, FileReader and
FileWriter.

• Internally FileReader uses


FileInputStream and
FileWriter uses
FileOutputStream
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 (buffer).
Commonly used methods of OutputStream class
Method Description

1) public void write(int)throws is used to write a byte to the


IOException current output stream.

2) public void write(byte[])throws is used to write an array of byte


IOException to the current output stream.

3) public void flush()throws flushes the current output


IOException stream.
4) public void close()throws is used to close the current
IOException output stream.
InputStream class
• InputStream class is an abstract class.

• It is the superclass of all classes representing an input stream of


bytes.
Commonly used methods of InputStream class
Method Description
1) public abstract int read()throws reads the next byte of data from
IOException the input stream. It returns -1 at
the end of file.
2) public int available()throws returns an estimate of the
IOException number of bytes that can be
read from the current input
stream.
3) public void close()throws is used to close the current input
IOException stream.
FileInputStream and FileOutputStream (File Handling)
• Java FileOutputStream class • Java FileInputStream class
▫ Java FileOutputStream is an ▫ Java FileInputStream class
output stream for writing data to obtains input bytes from a file.
a file. ▫ It is used for reading streams of
▫ If you have to write primitive raw bytes such as image data.
values then use ▫ For reading streams of characters,
FileOutputStream. consider using FileReader.
▫ Instead, for character-oriented • It should be used to read byte-
data, prefer FileWriter. oriented data for example to read
▫ But you can write byte-oriented as image, audio, video etc.
well as character-oriented data.
Example of Java FileOutputStream class
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s=“Dhoni is my favorite player";

//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:
Dhoni 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.

• The ByteArrayOutputStream holds a copy of data and forwards it to multiple


streams.

• The buffer of ByteArrayOutputStream automatically grows according to data.


Example for ByteArrayOutputStream
import java.io.*;
class S{
public static void main(String args[])throws Exception{
FileOutputStream fout1=new FileOutputStream("f1.txt");
FileOutputStream fout2=new FileOutputStream("f2.txt");

ByteArrayOutputStream bout=new ByteArrayOutputStream();


bout.write(139);
bout.writeTo(fout1);
bout.writeTo(fout2);

bout.flush();
bout.close();//has no effect
System.out.println("success...");
}
}
import java.io.*;
import java.util.*;

class B{

Java public static void main(String args[])throws IOException{

//creating the FileInputStream objects for all the files


SequenceInputStream FileInputStream fin=new FileInputStream("A.java");

class
FileInputStream fin2=new FileInputStream("abc2.txt");
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

• Java BufferedOutputStream class uses an internal


buffer to store data. It adds more efficiency than to
write data directly into a stream. So, it makes the
performance fast.

• Java BufferedInputStream class is used to read


information from stream. It internally uses buffer
mechanism to make the performance fast.
Example of BufferedOutputStream class
import java.io.*;
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("f1.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s=“Dhoni is my favourite player";
byte b[]=s.getBytes();
bout.write(b);

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{

InputStreamReader r=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name"); Output:


String name=br.readLine(); Enter your name Amit
System.out.println("Welcome "+name); Welcome Amit
}
}
Java Console class
• The Java Console class is be used to get input from console. It provides methods
to read text and password.

• 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.

• 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.

• Moreover, its methods don't throw IOException.

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.

Any applet in Java is a class that extends the java.applet.Applet class.

An Applet class does not have any main() method.

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.

4. As compared to stand-alone application applets are small in size, the advantage of


transferring it over network makes it more usable. No need of installations.

5. Applets are quite secure because of their restrictive access to resources.

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.

8. It can be executed by browsers running under many platforms, including Linux,


Windows, Mac OS etc.
Drawbacks of Applet
1. Java Plug-in is required at client browser to execute applet.

2. Security restrictions - Applets has no access to client-side resources


such as files , OS etc.
Applets cannot read/write local files, execute local programs, open arbitrary
network connections, etc.

3. Does not seem like a "regular" program

4. Applet has little restriction when it comes to communication - It can


communicate only with the machine from which it was loaded.

5. Applet cannot work with native methods.

6. Applet can only extract information about client-machine – What is its


name, java version, OS, version etc ... .

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().

3. Applets are designed to be embedded within an HTML page.

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.

• Each state is represented by a method. There exists 5 states represented by 5 methods.


▫ That is, in its life of execution, the applet exists (lives) in one of these 5 states.

• 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.

public void init(): is used to initialized the


Applet. It is invoked only once.
public void start(): is invoked after the
init() method or browser is maximized. It is
used to start the Applet.
public void stop(): is used to stop the
Applet. It is invoked when Applet is stop or
browser is minimized.
public void destroy(): is used to destroy
the Applet. It is invoked only once.
Applet Execution - Browser Role & Responsibilities
• The Applet Life Cycle methods are called as callback methods as
they are called implicitly by the browser for the smooth execution
of the applet.

• Browser should provide an environment known as container for


the execution of the applet.

• Following are the responsibilities of the browser.

1. It should call the callback methods at appropriate times for the


smooth execution of the applet.

2. It is responsible to maintain the Applet Life Cycle.

3. It should have the capability to communicate between applets,


applet to JavaScript and HTML, applet to browser etc.
Description of Applet Life Cycle Methods
init():
• The applet's voyage starts here.
• In this method, the applet object is created by the browser.
• Because this method is called before all the other methods,
programmer can utilize this method to instantiate objects,
initialize variables, setting background and foreground colors
in GUI etc.; the place of a constructor in an application.
• It is equivalent to born state of a thread.
• init() method is called at the time of starting the execution.
This is called only once in the life cycle.

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.*;

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.*;
import java.applet.*;

public class DisplayImage extends Applet


{
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
} <html> <body>
<applet code="DisplayImage.class"
width="300" height="300">
</applet> </body> </html>

• 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.
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");
}
}

You might also like