Escolar Documentos
Profissional Documentos
Cultura Documentos
Prepared by
Mr.S.Bhaggiaraj AP/IT,SREC.
5/16/2012 10:54:16 AM
Basics
Java IO operations are complex to understand but more powerful. These are the platform independent. These are stream based. Streams are flow of characters or bytes. An I/O Stream represents an input source or an output destination
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
Streams are the "fundamental element" of the java.io package A stream can represent many different kinds of sources and destinations disk files, devices, other programs, a network socket, and memory arrays
You cannot use them directly They define i/o in terms of bytes
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
Streams support many different kinds of data simple bytes, primitive data types, localized characters, and objects Some streams simply pass on data; others manipulate and transform the data in useful ways
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
No matter how they work internally, all streams present the same simple model to programs that use them A stream is a sequence of data Types:
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
InputStream
The sources from where data are read The sink to which the data are written. Deals the unicode characters (binary form) Deals the character oriented text.
6
OutputStream
Byte Stream
Character stream
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
Byte Stream
InputStream OutputStream
Reader
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
java.io
InputStream (abstact class)
ByteArrayInputStream
FileInputStream
FileOutputStream
InputStreamReader
OutputStreamWriter
ObjectInputStream
ObjectOutputStream
StringReader
StringWriter
PipedInputStream
PipedOutputStream
CharArrayReader
CharArrayWriter
FilterInputStream
FilterOutputStream
PipedReader
PipedWriter
BufferedInputStream
BufferedOutputStream
FilterReader FileReader
FilterWriter FileWriter
DataInputStream
5/16/2012 10:54:17 AM
DataOutputStream
MR.S.BHAGGIARAJ AP/IT,SREC
InputStream Methods
Method
abstract int read( ) int read(byte b[ ] ) int available( ) void close( )
Purpose
Reads one byte and returns an int representation of that byte. Reads into an array of bytes b and returns the number of bytes read. Returns number of bytes available for reading Closes the input stream
void mark( int marklen) Puts a mark at the current position and remembers it until marklen bytes are read.
void reset( ) long skip(long n) The read control is reset to the previous set mark. Subsequent read( ) will reread these bytes. Skips n bytes of the input stream and returns the actual number of bytes skipped
5/16/2012 10:54:17 AM
MR.S.BHAGGIARAJ AP/IT,SREC
OutputStream Methods
Method Purpose
5/16/2012 10:54:17 AM
MR.S.BHAGGIARAJ AP/IT,SREC
10
Reader Methods
Method
void close( ) int read( ) int read( char c[ ] ) boolean ready( )
Purpose
Close the input reader. Returns an integer value equivalent to next available character. Read character into an array c [ ]. Returns true if next input request will not wait, otherwise false
Makes a mark at the current position and remembers it intil c are read.
Resets the input pointer to the previously mark position. Skips n characters and returns the actual number of characters skipped
5/16/2012 10:54:17 AM
MR.S.BHAGGIARAJ AP/IT,SREC
11
Writer Methods
Method
void write( int b)
Purpose
Writes a single character to the stream
5/16/2012 10:54:17 AM
MR.S.BHAGGIARAJ AP/IT,SREC
12
BufferedReader.
It is a subclass of Reader. It can not directly access any source. Methods can be used to read characters, store them in buffer and send the buffer to destination. Constructor in the class:
13
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
BufferedReader.
BufferedReader(Reader r)
Creates a buffering character input stream using a default buffer for underlying reader stream r. Creates a buffering character input stream using a buffer size of size.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
14
BufferedReader.
Inherits the methods from Reader. Additional method defined in this class is readLine(). It reads characters from an underlying character stream. It returns string.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
15
BufferedWriter.
It is subclass of Writer. Inherits method from writer class. Methods can be used to write characters, sending them for each write. Additional method is newLine( ) It generate the newline(\n).
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
16
BufferedWriter(Writer out)
Creates a buffered character output stream using a default buffer size. Creates a buffered character output stream using a buffer size of size.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
17
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
18
DataOutputStream dous= new DataOutputStream(new BufferedOutputStream (new FileOutputStream(fou))); do { System.out.print( ur name,addr1,addr2,pin and state one by one:); name=br.readLine(); addr1=br.readLine(); addr2=br.readLine(); pin=br.readLine(); state=br.readLine();
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
19
dous.WriteBytes(name); dous.WriteBytes(addr1); dous.WriteBytes(addr2); dous.WriteBytes(pin); dous.WriteBytes(state); System.out.println( to continue press y otherwise press n); choice =br.readLine( ); if( choice.equals(n) || choice.equals(N)) more=false; }while(more);
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
20
dous.close( ); } catch(FileNotFoundException e) { System.out.println(\n File not found); } catch(IOException e) { System.out.println(\n I / O problem); } }// end of main } // end of the class
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
21
File to know the details of file. BufferedReaderto read character stream InputStreamReaderto covert byte to character stream DataOutputStreamto convert basic types to bytes and pass to o/p stream. BufferedOutputStreamto send buffered bytes to o/p stream. FileOutputStreamto write bytes into disk file.
22
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
Examle 2:
import java.io.*; public class OutputExample{ public static void main(String args[]){ if(ars.length == 0){ System.out.println("String argument needed."); System.exit(1); } String word = args[0]; try{ BufferedWriter bw = new BufferedWriter( new FileWriter("output.txt")); Creates new file. If it exits it will be deleted and a new file is created
23
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
Example 2:
for(int i = 0; i < word.length(); i++){ ans += word.substring(i); bw.write(ans); bw.newLine(); ans = ""; } bw.close(); }catch(Exception e){} } //main } //class
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
24
Example 3:
import java.io.*; import java.util.*; public class InputExample{ public static void main(String args[]){ StringTokenizer st; try{ BufferedReader br = new BufferedReader( new FileReader("input1.txt")); String line = br.readLine(); double avg = 0.0; int num = 0, count = 0; while(line != null){ st = new StringTokenizer(line);
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
25
Example 3:
for(int i = 0; i < st.countTokens(); i++){ avg += Double.parseDouble(st.nextToken()); count++; } line = br.readLine(); } br.close(); avg = avg/count; System.out.println("Avg: " + avg); }catch(Exception e){} } //main } //class
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
26
StringTokenizer
Breaks up the string into tokens. It implements the enumeration interface. The input string contains the delimiter. The delimiters are characters that separate the tokens. The nextToken() method is used to extract the consecutive tokens.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
27
Unit II---Thread
5/16/2012 10:54:16 AM
28
Multitasking
More than one task is processed. Utilize the CPU time more efffectively. Each task has its set of variable and separate memory location.
CPU TIME
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
29
Multithreading
A single task is sub divided into many sub task. Each sub task is carried out one after another. For example reading input, processing them, storing them, drawing them and etc. Idle time of CPU can be effectively used in multitasking.
30
Comparison
Multitasking
Deals the N number of tasks
It has Same set of variable and separate memory location
Multithreading
Deals the n number of sub tasks.
It has same set of variable and memory location.
IPC is expensive & more Context IPC is inexpensive & less context switching switching
5/16/2012 10:54:17 AM
MR.S.BHAGGIARAJ AP/IT,SREC
31
ThreadDefinition.
Light weight process. Single sequential flow of control within a program. A semi-process with a definite starting point, an execution sequence and a terminating point. It maintains its own stack where it keeps the exception handlers, the scheduling priority and other details that the system might need to reactivate that thread.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
32
A thread is a real thing with a beginning, a sequence of operations that it will execute and an end. It has a beginning, a body, and an end, and executes commands sequentially. In fact all main programs in our earlier examples can be called single-threaded programs. Every program will have at least one thread
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
33
Why threads?
For example
Certain sub tasks like reading an i/p stream, may have to keep waiting till a byte is read. In such occasions, the CPU will be idle without doing any work. That time can be utilized by some other sub task, say printing, storing and etc.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
34
Creating Thread
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
35
Creating Thread
In the first way, define a class that extends Thread class and override its run () method with the code required by the thread. Regarding second way, define a class that implements Runnable interface. The runnable interface has only one method, run (), that is to be defined n the method with the code to be executed by the thread.
5/16/2012 10:54:16 AM MR.S.BHAGGIARAJ AP/IT,SREC
36
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
37
38
The run () method has been inherited by the mythread.we have to override the run () method ,in order to implement the code to be executed by our thread.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
39
First creates an object for the thread class by using new operator.
Second calls the start () method causing the thread to move into the runnable state. Then the java runtime will schedule the thread to run by invoking its run () method. Now, the thread is said to be in the running state.
40
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
import java.lang.Thread; class threadA extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("\nFrom Thread A:i="+i); } System.out.println("Exit from A"); } }
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
41
class threadB extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("\nFrom Thread B:j="+j); } System.out.println("Exit from B"); }
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
42
class threadC extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("\nFrom Thread C:k= "+k); } System.out.println("Exit from C"); } }
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
43
public class Threadtest { public static void main(String g[]) { new threadA().start(); new threadB().start(); new threadC().start(); } }
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
44
output
start thread A start thread B From Thread A:i=1 start thread c From Thread A:i=2 From Thread A:i=3 From Thread A:i=4 From Thread A:i=5 Exit form A From thread c:K=1 From Thread B:j=1 From Thread B:j=2 From Thread B:j=3 exit from C From thread c:K=2 exit from C From thread c:K=3 exit from C From thread c:K=4 exit from C From thread c:K=5 exit from C BUILD SUCCESSFUL (total time: 1 second) start thread A start thread B From Thread A:i=1 From Thread A:i=2 start thread c From Thread B:j=1 From Thread A:i=3 From Thread B:j=2 From Thread A:i=4 From Thread B:j=3 From Thread A:i=5 Exit form A From thread c:K=1 exit from C From thread c:K=2 exit from C From thread c:K=3 exit from C From thread c:K=4 exit from C From thread c:K=5 exit from C BUILD SUCCESSFUL (total time: 1 second)
5/16/2012 10:54:17 AM
MR.S.BHAGGIARAJ AP/IT,SREC
45
1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state
46
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
Transition diagram
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
47
Newborn State
When we create a thread object, the thread is born and is said to be in newborn state. At this state, we can do only one of the following things with it.
Schedule it for running using start () method. Kill it using stop () method.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
48
Runnable State
In this state ,the thread is ready for execution and is waiting for the availability of the processor. That is the thread has joined the queue of threads that are waiting for execution. If all the threads have equal priority,then they are given time slots for execution in first come,first serve manner.
49
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
Running State
Running means that the processor has given its time to the thread for its execution. There are certain situations in the running state .
1.
2. 3.
It has been suspended using suspend() method. It has been made to sleep. It has been told to wait until some event occurs
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
50
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
51
We can put a thread to sleep for specified time period using sleep () method where time is milliseconds. The thread re-enters the runnable state as soon as this time period is elapsed
5/16/2012 10:54:16 AM MR.S.BHAGGIARAJ AP/IT,SREC
52
This is done using the wait () method. The thread can be scheduled to run again using the notify () method.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
53
STOPPING A THREAD
By using stop () method ,we can stop the thread from the running. Objectname.stop(); This statement causes the thread to move to the dead state. Automatically move to dead state when it reaches the end of its method.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
54
BLOCKING A THREAD
Temporarily suspended or blocked from entering into the runnable subsequently running state by using either of the following thread methods.
Sleep () //blocked for a specified time Suspend () //blocked until further orders Wait() //blocked until certain condition occurs
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
55
Dead State
Every thread has a lifecycle. If run () method has completed executing, then thread has been gone. Or if run () method has aborted due to occurrence of any exception and then thread has been gone. It is natural death.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
56
Controlling thread
The yield(),sleep() methods. static void yield()
Causes the running thread to yield to other runnable thread Makes the thread to sleep for ms time.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
57
THREAD PRIORITY
Each thread is assigned a priority Affects the order in which it is scheduled for running. same priority are given equal treatment by the java scheduler and, therefore, they share the processor on a FIFO basis. The priority is an integer between 1 and 10
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
58
setPriority method: This method is called on a Thread object with an int between 1 and 10 as the only input parameter.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
59
getPriority method :
returns the priority of the thread, referenced by the Thread object, as an int.
Example class Sumthread implements Runnable { int i,sum=0; public void run() { for(i=1;i<=5;i++) {
MR.S.BHAGGIARAJ AP/IT,SREC
5/16/2012 10:54:16 AM
60
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
61
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
62
class Threadpriority { public static void main(String a[]) { Sumthread st=new Sumthread(); Factthread ft=new Factthread(); Thread sumt=new Thread(st, Sum thread); Thread factt=new Thread(ft, Factorial thread);
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
63
sumt.setPriority(Thread.NORM_PRIORITY-2); factt.setPriority(Thread.NORM_PRIORITY+2); System.out.println(The created Thread is +sumt.getName()); System.out.println(The created Thread is +Factt.getName()); System.out.println(Priority value of +sumt.getName + is+ sumt.getPrority()); System.out.println(Priority value of +factt.getName+ is +factt.getPrority());
sumt.start(); Factt.start(); } }
5/16/2012 10:54:16 AM MR.S.BHAGGIARAJ AP/IT,SREC
64
Output
The created Thread is Sum thread The created Thread is Factorial thread Priority value of Sum thread is=3 Priority value of Factorial thread is=7 Factorial of 1=1 Factorial of 2=2 Factorial of 3=6 Factorial of 4=24 Factorial of 5=120
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
65
Output
Sum of the numbers from 1 upto 1=1 Sum of the numbers from 1 upto 2=3 Sum of the numbers from 1 upto 3=6 Sum of the numbers from 1 upto 4=10 Sum of the numbers from 1 upto 5=15
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
66
Synchronized Methods
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
67
Synchronized Methods
Java creates a monitor and hands it over to the thread that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code. A monitor is like a key and the thread that holds the key can only open the lock.
68
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
Synchronized Methods
It will handover the monitor to the next thread when it is completed. Dead Lock Assume that the methods1 until it gets hold of method2. Because these are mutually exclusive conditions, a deadlock occurs (two or more threads are waiting to control of resource).
69
Synchronized Methods
Thread A Synchronized method2() { synchronized method1() { .. } } Thread B Synchronized method1() { synchronized method2() { .. } }
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
70
Reader is a..
a) b) c)
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
71
A thread is a.
a) b) c)
d)
Heavy weight process. More overhead It has different set of variable and memory location. Less context switching
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
72
True False
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
73
True False
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
74
b)
c)
d)
Start() is used to run the suspended thread. Kill() is used to terminate the thread. Normal priority is a average of any two thread priority. Less context switching
1. 2. 3. 4.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
Java creates a monitor and hands it over to the thread that calls the method first time.
a) b)
True. False.
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
76
ThreadName.setPriority ( int number); setPriority ( int number); setPriority = number; ThreadName.setPriority= number;
5/16/2012 10:54:16 AM
MR.S.BHAGGIARAJ AP/IT,SREC
77