1
JAVA PROGRAMMING UNIT-IV:
Multithreading: introduction, thread life cycle, creation of threads, thread priorities, thread
synchronization, communication between threads. Reading data from files and writing data to
files, random access file.
The earlier days the computer’s memory is occupied only one program after completion
of one program it is possible to execute another program is called uniprogramming.
Whenever one program execution is completed then only second program execution will
be started such type of execution is called cooperative execution, this execution we are having lot
of disadvantages.
Most of the times memory will be wasted.
CPU utilization will be reduced because only program allow executing at a time.
The program queue is developed on the basis cooperative execution
To overcome above problem a new programming style will be introduced is called
multiprogramming.
1) Multiprogramming means executing the more than one program at a time.
2) All these programs are controlled by the CPU scheduler.
3) CPU scheduler will allocate a particular time period for each and every program.
4) Executing several programs simultaneously is called multiprogramming.
5) In multiprogramming a program can be entered in different states.
a. Ready state.
b. Running state.
c. Waiting state.
6) Multiprogramming mainly focuses on the number of programs.
Advantages of multiprogramming:-
1. CPU utilization will be increased.
2. Execution speed will be increased and response time will be decreased.
2
3. CPU resources are not wasted.
Multiprogramming cam be majorly done in two ways
1. Multiprocessing
2. Multithreading
Definition of Multiprocessing
A multiprocessing system is one which has more than two processors. The CPUs are added to
the system to increase the computing speed of the system. Each CPU has its own set of registers
and main memory. Just because CPUs are separate, it may happen that one CPU must not have
anything to process and may sit idle and the other may be overloaded with the processes. In such
cases, the processes and the resources are shared dynamically among the processors.
Definition of Multithreading
Multithreading is the execution of multiple threads of a single process concurrently within the
context of that process. Now let us first discuss what is a thread? A thread of a process means a
code segment of a process, which has its own thread ID, program counter, registers and stacks
and can execute independently. But threads belonging to the same process have to share the
belongings of that process like code, data, and system resources. Creating separate processes for
each service request consumes time and exhaust system resources. Instead of incurring this
overhead, it is more efficient to create threads of a process.
3
To understand the multithreading concept let us take an example of a word processor. A word
processor, displays graphic, responds to keystrokes, and at the same time, it continues spelling
and grammar checking. You do not have to open different word processors to do this
concurrently. It does get happen in a single word processor with the help of multiple threads.
BASIS FOR
COMPARISON
MULTIPROCESSING MULTITHREADING
Basic Multiprocessing adds CPUs to
increase computing power.
Multithreading creates
multiple threads of a single
process to increase computing
power.
Execution Multiple processes are
executed concurrently.
Multiple threads of a single
process are executed
concurrently.
Creation Creation of a process is time-
consuming and resource
intensive.
Creation of a thread is
economical in both sense time
and resource.
4
Classification Multiprocessing can be
symmetric or asymmetric.
Multithreading is not
classified.
So finally we came to know that multi-threading is more advantages then multiprocessing
Let see what is a process and Thread
A program in execution is often referred as process. A thread is a subset (part) of the process.
A process consists of multiple threads. A thread is a smallest part of the process that can execute
concurrently with other parts (threads) of the process.
A process is sometime referred as task. A thread is often referred as lightweight process.
Thread:-
1) Thread is nothing but separate path of sequential execution.
2) The independent execution technical name is called thread.
3) Whenever different parts of the program executed simultaneously that each and every part is
called thread.
4) The thread is light weight process because whenever we are creating thread it is not occupying
the separate memory it uses the same memory. Whenever the memory is shared means it is not
consuming more memory.
5) Executing more than one thread a time is called multithreading.
The main important application areas of the multithreading are
1. Developing video games
2. Implementing multimedia graphics.
3. Developing animations
There are two different ways to create a thread is avilable
1) Create class that extending standard java.lang.Thread Class
2) Create class that Implementing java.lang.Runnable interface
3) By using Anonymous inner class
First methodology:
class Runner extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
5
public class ApplicationExtends {
public static void main(String[] args) {
Runner runner1 = new Runner();
runner1.start();
Runner runner2 = new Runner();
runner2.start();
}
}
Second methodology
class RunnerRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ApplicationRunnable {
public static void main(String[] args) {
for(int j=0;j<5;j++){
System.out.println("hello main thread");
}
Thread thread1 = new Thread(new RunnerRunnable());
Thread thread2 = new Thread(new RunnerRunnable());
thread1.start();
thread2.start();
}
}
One more methodology is there by using anonymous inner classes
public class ApplicationAnonymous {
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
6
System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
}
}
});
thread1.start();
}
}
Note:
1) Whenever we are calling t.start() method the JVM search for the start() in the MyThread class
but the start() method is not present in the MyThread class so JVM goes to parent class called
Thread class and search for the start() method.
2) In the Thread class start () method is available hence JVM is executing start() method.
3) Whenever the thread class start() that start() is responsible person to call run() method.
4) Finally the run() automatically executed whenever we are calling start() method.
5) Whenever we are giving a chance to the Thread class start() method then only a new thread
will be created.
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. The following diagram shows the complete life cycle of a thread.
Following are the stages of the life cycle −
New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread
in this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only
when another thread signals the waiting thread to continue executing.
7
Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
Thread Scheduler:-
Thread scheduler is a part of the JVM. It decides which thread is executed first and which thread
is executed next.
Only one thread is executed at a time.
We can’t expect exact behavior of the thread scheduler it is JVM vendor dependent. So we can’t
expect output of the multithreaded examples we can say the possible outputs.
Thread Scheduler mainly uses preemptive (or) time slicing to schedule the threads.
Preemptive scheduling:-
In this highest priority task is executed first after this task enters into waiting state or dead state
then only another higher priority task come to existence.
Time Slicing Scheduling:-
A task is executed predefined slice of time and then return pool of ready tasks. The scheduler
Determines which task is executed based on the priority and other factors.
Difference between t.start() and t.run():-
In the case of t.start(), Thread class start() is executed a new thread will be created that is
responsible for the execution of run() method.
But in the case of t.run() method, no new thread will be created and the run() is executed like a
normal method call by the main thread.
Thread Priorities:-
1. Every Thread in java has some priority. It may be default priority provided be the JVM or
customized priority provided by the programmer.
2. The valid range of thread priorities is 1 – 10. Where one is lowest priority and 10 is highest
priority.
3. The default priority of main thread is 5. The priority of child thread is inherited from the
parent.
4. Thread defines the following constants to represent some standard priorities.
5. Thread Scheduler will use priorities while allocating processor the thread which is having
highest priority will get chance first and the thread which is having low priority.
6. If two threads having the same priority then we can’t expect exact execution
order it depends upon Thread Scheduler.
7. The thread which is having low priority has to wait until completion of high priority threads.
8. Three constant values for the thread priority.
8
a. MIN_PRIORITY = 1
b. NORM_PRIORITY = 5
c. MAX_PRIORITY = 10
Thread class defines the following methods to get and set priority of a Thread.
a. Public final int getPriority()
b. Public final void setPriority(int priority)
Here ‘priority’ indicates a number which is in the allowed range of 1 – 10. Otherwise we will get
Runtime exception saying “IllegalArgumentException”.
Ex:-
class Thread1 extends Thread
{
public void run()
{
System.out.println("Enter into thread 1");
System.out.println ("thread 1 is started");
for (int i=0;i<10 ;i++ )
{
System.out.println ("Thread 1");
}
System.out.println ("thread 1 is ended");
}
}
class Thread2 extends Thread
{
public void run()
{
System.out.println("Enter into thread 2");
System.out.println("thread 2 is started");
for (int i=0;i<10 ;i++ )
{
System.out.println("Thread 2");
}
System.out.println("thread 2 is ended"); }
}
class ThreadDemo
{
public static void main(String[] a)
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
9
t1.setPriority(Thread.MAX_PRIORITY);
System.out.println(t1.getPriority());
t2.setPriority(Thread.MIN_PRIORITY);
System.out.println(t2.getPriority());
t1.start();
System.out.println("starting of Thread1");
t2.start();
System.out.println("starting of Thread1");
}
}
Some of the thread class methods:-
Sleep():-
The sleep()method causes the current thread to sleep for a specified amount of time in
milliseconds.
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis,int nanosec) throws InterruptedException
Java.lang.Thread.yield():-
Yeald() method causes to pause current executing Thread for giving the chance for
waiting threads of same priority.
If there are no waiting threads or all threads are having low priority then the same thread
will continue its execution once again.
Syntax:-
Public static native void yield();
Java.lang.Thread.join():-
If a Thread wants to wait until completing some other thread then we should go for join()
method.
1. Public final void join()throws InterruptedExcetion
2. Public final void join(long ms)throws InterruptedException
3. Public final void join(long ms, int ns)throws InterruptedException
isAlive():-
used to check whether the thread is live or not. Public Boolean isAlive()
Java.lang.Thread.activeCount():-
This method is used to find out the number of methods in active state.
Public static int activeCount();
Java.lang.currentThread():-
This method is used to represent current thread class object.
Public static thread currentThread()
Java.lang.Thread.getId():-
getId() is used to generate id value for each and every thread.
Public long getId()
Interrupted():-
A thread can interrupt another sleeping or waiting thread.
10
For this Thread class defines interrupt() method.
Public void interrupt()
Effect of interrupt() method call:-
class MyThread extends Thread
{
public void run()
{
try
{
for (int i=0;i<10;i++ )
{
System.out.println("i am sleeping ");
Thread.sleep(5000);
}
}
catch (InterruptedException ie)
{
System.out.println("i got interupted by interrupt() call");
}
}
};
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
t.interrupt();
}
}
NOTE:-
The interrupt() is working good whenever our thread enters into waiting state or sleeping
state.
The interrupted call will be wasted if our thread doesn’t enters into the waiting/sleeping
state.
Synchronized:-
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
11
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Why use Synchronization
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1 .Synchronized method.
2. Synchronized block.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by three ways in java:
1. by synchronized method
2. by synchronized block
Concept of Lock in Java
Synchronization is built around an internal entity known as the lock or monitor. Every object has
an lock associated with it. By convention, a thread that needs consistent access to an object's
fields has to acquire the object's lock before accessing them, and then release the lock when it's
done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.
Java synchronized method
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
1. //example of java synchronized method
2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
12
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }
Note: Refer program which we discussed about MethodSynchrization in java
13
Synchronized block in java
Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you
can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression) {
//code block
}
1. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. class MyThread1 extends Thread{
16. Table t;
17. MyThread1(Table t){
18. this.t=t;
19. }
20. public void run(){
21. t.printTable(5);
22. }
23.
24. }
14
25. class MyThread2 extends Thread{
26. Table t;
27. MyThread2(Table t){
28. this.t=t;
29. }
30. public void run(){
31. t.printTable(100);
32. }
33. }
34.
35. public class TestSynchronizedBlock1{
36. public static void main(String args[]){
37. Table obj = new Table();//only one object
38. MyThread1 t1=new MyThread1(obj);
39. MyThread2 t2=new MyThread2(obj);
40. t1.start();
41. t2.start();
42. }
43. }
Note:Refer program which we discussed about SynchrizationBlocks in java
Important Points to Remember about Synchronization:
Synchronized modifier is the modifier applicable for methods but not for classes and
variables.
If a method or a block declared as synchronized then at a time only one Thread is allowed
to operate on the given object.
The main advantage of synchronized modifier is we can resolve data inconsistency
problems.
But the main disadvantage of synchronized modifier is it increases the waiting time of the
Thread and effects performance of the system .Hence if there is no specific requirement it
is never recommended to use.
The main purpose of this modifier is to reduce the data inconsistence problems.
Producer Consumer Problem:
In computing, the producer–consumer problem (also known as the bounded-buffer problem) is a
classic example of a multi-process synchronization problem. The problem describes two
processes, the producer and the consumer, which share a common, fixed-size buffer used as a
queue.
The producer’s job is to generate data, put it into the buffer, and start again.
15
At the same time, the consumer is consuming the data (i.e. removing it from the buffer),
one piece at a time.
Same Example of synchronized block by using annonymous class:
1. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14. 15. public class TestSynchronizedBlock2{
16. public static void main(String args[]){
17. final Table obj = new Table();//only one object
18. 19. Thread t1=new Thread(){
20. public void run(){
21. obj.printTable(5);
22. }
23. };
24. Thread t2=new Thread(){
25. public void run(){
26. obj.printTable(100);
27. }
28. };
29. t1.start();
30. t2.start();
31. }
32. }
Problem To make sure that the producer won’t try to add data into the buffer if it’s full and that
the consumer won’t try to remove data from an empty buffer.
Solution The producer is to either go to sleep or discard data if the buffer is full. The next time
the consumer removes an item from the buffer, it notifies the producer, who starts to fill the
buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty.
The next time the producer puts data into the buffer, it wakes up the sleeping consumer. An
inadequate solution could result in a deadlock where both processes are waiting to be awakened.
Note : Refer Program which we Discussed inside the class ProducerConsumer in JAVA
16
Daemon threads:-
The threads which are executed at background is called daemon threads. Ex:- garbage
collector,ThreadSchedular.default exceptional handler.
Non-daemon threads:-
The threads which are executed fore ground is called non-daemon threads.
Ex:- normal java application.
Volatile:-
Volatile modifier is also applicable only for variables but not for methods and classes.
If the values of a variable keep on changing such type of variables we have to declare
with volatile modifier.
If a variable declared as a volatile then for every Thread a separate local copy will be
created.
Every intermediate modification performed by that Thread will take place in local copy
instead of master copy.
Once the value got finalized just before terminating the Thread the master copy value will
be updated with the local stable value. The main advantage of volatile modifier is we can
resolve the data inconsistency problem.
But the main disadvantage is creating and maintaining a separate copy for every Thread
Increases the complexity of the programming and effects performance of the system.
Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.
Inter-thread communication in Java
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in
its critical section and another thread is allowed to enter (or lock) in the same critical section to
be executed. It is implemented by following methods of Object class:
17
wait()
notify()
notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait()throws
InterruptedException
waits until object is notified.
public final void wait(long timeout)throws
InterruptedException
waits for the specified amount of time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
Understanding the process of inter-thread communication
The point to point explanation of the above diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
18
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases
the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
wait(), notify() and notifyAll() methods are defined in Object class not Thread class because they
are related to lock and object has a lock.
Difference between wait and sleep?
Let's see the important differences between wait and sleep methods.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is
completed.
Example of inter thread communication in java
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14. 15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
19
20. }
21. }
22. 23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32. 33. }}
Reading data from files and writing data to files
JAVA IO (Input and Output)
Java.io is a package which contains number of classes by using that classes we are able to send
the data from one place to another place.
In java language we are transferring the data in the form of two ways:-
1. Byte format
2. Character format
Stream/channel:-
It is acting as medium by using steam or channel we are able to send particular data from one
place to another place.
Streams are two types:-
1. Byte oriented streams.(supports byte formatted data to transfer)
2. Character oriented stream.(supports character formatted data to transfer)
Byte oriented streams:-
Java.io.FileInputStream
To read the data from the destination file to the java application we have to use FileInputSream
class.
To read the data from the .txt file we have to read() method.
20
Java.io.FileOutputStream:-
To write the data to the destination file we have to use the FileOutputStream.
To write the data to the destination file we have to use write() method.
Ex:- byte oriented streams in java Example (one character at a time).
import java.io.*;
class Test
{
static FileInputStream fis;
static FileOutputStream fos;
public static void main(String[] args)
{
try{
fis=new FileInputStream("get.txt");
fos=new FileOutputStream("set.txt",true); int c;
while ((c=fis.read())!=-1)
{
fos.write(c);
}
fis.close();
fos.close();
}
catch(IOException io)
{
System.out.println("getting IOException");
}
21
}
}
Ex:- :- charecter oriented streams in java Example (one character at a time).
import java.io.*;
class Test
{
static FileReader fr;
static FileWriter fw;
public static void main(String[] args)
{
try{
fr=new FileReader("get.txt");
fw=new FileWriter("set.txt",true);
int c;
while ((c=fr.read())!=-1)
{
fw.write(c);
}
fr.close();
fw.close();
}
catch(IOException io)
{
System.out.println("getting IOException");
}
}
}
Line oriented I/O:-
Character oriented streams supports single character and line oriented streams supports single
line data.
BufferedReader:- to read the data line by line format and we have to use readLine() to read the
data.
PrintWriter :- to write the data line by line format and we have to use println() to write the data.
import java.io.*;
class Test
{
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args)
{
22
try{
br=new BufferedReader(new FileReader("get.txt"));
pw=new PrintWriter(new FileWriter("set.txt"));
String line;
while ((line=br.readLine())!=null)
{
pw.println(line);
}
br.close();
pw.close();
}
catch(IOException io)
{
System.out.println("getting IOException");
}
}
}
Buffered Streams:-
Up to we are working with non buffered streams these are providing less performance because
these are interact with the hard disk, network.
Now we have to work with Buffered Streams
BufferedInputStream read the data from memory area known as Buffer.
We are having four buffered Stream classes
1. BufferedInputStream
2. BufferedOutputStream
3. BufferedReader
4. BufferedWriter
Ex:-
import java.io.*;
class Test
{
static BufferedReader br;
static BufferedWriter bw;
public static void main(String[] args)
{
try{
br=new BufferedReader(new FileReader("Test1.java")); bw=new BufferedWriter(new
FileWriter("States.java")); String str;
while ((str=br.readLine())!=null)
{
23
bw.write(str);
}
br.close();
bw.close();
}
catch(Exception e)
{
System.out.println("getting Exception");
}
}
}
Ex:-
import java.io.*;
class Test
{
static BufferedInputStream bis;
static BufferedOutputStream bos;
public static void main(String[] args)
{
try{
bis=new BufferedInputStream(new FileInputStream("abc.txt")); bos=new
BufferedOutputStream(new FileOutputStream("xyz.txt"));
int str;
while ((str=bis.read())!=-1)
{
bos.write(str);
}
bis.close();
bos.close();
}
catch(Exception e)
{
System.out.println(e); System.out.println("getting Exception");
}
}
}
Ex:-
import java.io.*;
class Test
24
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new FileReader("abc.txt"));
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
}
}
Java.util.Scanner:-
By using Scanner class we are able to divide the String into the number of tokens. To get the
integer value from the keyboard-------:-s.nextInt()
To get the String value from the keyboard---------:-s.next()
To get the floating values from the keyboard------:-s.nextFloat ();
Serialization:-
The process of saving an object to a file (or) the process of sending an object across the network
is called serialization.
But strictly speaking the process of converting the object from java supported form to the
network supported form.
To do the serialization we required fallowing classes
1. FileOutputStream
2. ObjectOutputStream
Deserialization:-
The process of reading the object from file supported form or network supported form to the java
supported form is called deserialization.
We can achieve the deserialization by using fallowing classes.
1. FileInputStream
2. ObjectInputStream
Note : To do serialization we need to implement Serializable interface
Transient Modifiers
Transient modifier is the modifier applicable for only variables and we can’t apply for
methods and classes.
At the time of serialization, if we don’t want to save the values of a particular variable to
meet security constraints then we should go for transient modifier.
At the time of serialization JVM ignores the original value of transient variable and
default value will be serialized.
25
Java.io.RandomAccessFile Class
Java RandomAccessFile provides facility to both read and write data to a file.
RandomAccessFile works with file as large array of bytes stored in the file system and a cursor
using which we can move the file pointer position.
RandomAccessFile class is part of Java IO. While creating the instance of RandomAccessFile in
java, we need to provide the mode to open the file. For example, to open the file for read only
mode we have to use “r” and for read-write operations we have to use “rw”.
Using file pointer, we can read or write data from random access file at any position. To get the
current file pointer, you can call getFilePointer () method and to set the file pointer index, you
can call seek (int i) method.
If we write data at any index where data is already present, it will override it.
Java RandomAccessFile read example
We can read byte array from a file using RandomAccessFile in java. Below is the pseudo code to
read file using RandomAccessFile.
RandomAccessFile raf = new RandomAccessFile("file.txt", "r");
raf.seek(1);
byte[] bytes = new byte[5];
raf.read(bytes);
raf.close();
System.out.println(new String(bytes));
In first line, we are creating RandomAccessFile instance for file in read-only mode.
Then in second line, we are moving the file pointer to index 1.
We have created byte array of length 5, so when we are calling read(bytes) method then 5 bytes
are read from file to the byte array.
Finally we are closing the RandomAccessFile resource and printing the byte array to console.
Java RandomAccessFile write example
Here is a simple example showing how to write data to a file using RandomAccessFile in java.
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(5);
raf.write("Data".getBytes());
raf.close();
Since RandomAccessFile treats file as byte array, write operation can override the data as well as
it can append to a file. It all depends on the file pointer position. If the pointer is moved beyond
the file length and then write operation is called, then there will be junk data written in the file.
So you should take care of this while using write operation.
RandomAccessFile append example
All we need is to make sure file pointer is at the end of file to append to a file. Below is the code
for append to file using RandomAccessFile.
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
26
raf.seek(raf.length());
raf.write("Data".getBytes());
raf.close();
Java RandomAccessFile Example
Here is a complete java RandomAccessFile example with different read and write operations.
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
public static void main(String[] args) {
try {
// file content is "ABCDEFGH"
String filePath = "source.txt";
System.out.println(new String(readCharsFromFile(filePath, 1, 5)));
writeData(filePath, "Data", 5);
//now file content is "ABCDEData"
appendData(filePath, "javafile");
//now file content is "ABCDEDatajavafile"
} catch (IOException e) {
e.printStackTrace();
}
}
private static void appendData(String filePath, String data) throws IOException {
RandomAccessFile raFile = new RandomAccessFile(filePath, "rw");
raFile.seek(raFile.length());
System.out.println("current pointer = "+raFile.getFilePointer());
raFile.write(data.getBytes());
raFile.close();
}
private static void writeData(String filePath, String data, int seek) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(seek);
file.write(data.getBytes());
file.close();
}
private static byte[] readCharsFromFile(String filePath, int seek, int chars) throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(seek);
byte[] bytes = new byte[chars];
27
file.read(bytes);
file.close();
return bytes;
}
}