Professional Documents
Culture Documents
Java Module 5
Java Module 5
Multithreading
A thread is similar to a program that has single flow of control. It has a beginning, a body and an end and
execute commands sequentially. All the main programs in our earlier examples can be called single
threaded programs. Every program will have at least one thread as shown below.
class Chakry Begin
{
........
........
Single Threaded body of
........ execution
....
.. End
}
A program that contains multiple flows of control is known as multithreaded program. The following diagram shows
a java program with four threads, one main thread and three others.
Main Thread
switching switching
Thread A Thread B Thread C
What is Thread?
A thread is a single sequential flow of control within a program.
A thread is a lightweight sub-process, the smallest unit of processing.
Multithreading in Java is a process of executing multiple threads simultaneously.
Multithreading use a shared memory area, they don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than process.
It differs from a “process” in that a process is a program executing in its own address space whereas
a thread is a single stream of execution within a process.
Java Multithreading is mostly used in games, animation, etc.
The run() method should be invoked by an object of the concerned thread. This can be achieved by creating
the thread and initiating it with the help of another thread method called “start()”. Some of the methods
which are available in Thread class as shown below:
S.N Modifier Method Description
o and Type
3) static void sleep() It sleeps a thread for the specified amount of time.
12) static void yield() It causes the currently executing thread object to pause and allow
other threads to execute temporarily.
16) void destroy() It is used to destroy the thread group and all of its subgroups.
18) void notify() It is used to give the notification for only one thread which is
waiting for a particular object.
19) void notifyAll() It is used to give the notification to all waiting threads of a
particular object.
2
UNIT V
A thread is always in one of these 5 states. It can move from one state to another in many ways as
shown below.
New Thread New Born
stop( )
start( )
stop( )
Active Thread Running Runnable Killed Thread
Dead
yield()
sleep( ) resume( )
suspend( ) notify( ) stop( )
wait( )
Idle Thread Blocked
( Not
( Not Run)
Runnable)
( Not Run)
1. New born state: In this phase, the thread is created using class "Thread class". It remains in this state till
the program starts the thread. It is also known as born thread.
2. Runnable state: In this state, the instance of the thread is invoked with a start() method. The thread
control is given to scheduler to finish the execution. It depends on the scheduler, whether to run the
thread.
3. Running state: When the thread starts executing, then the state is changed to "running" state. The
scheduler selects one thread from the thread pool, and it starts executing in the application.
4. Waiting(Blocked) state: This is the state when a thread has to wait. As there multiple threads are
running in the application, there is a need for synchronization between threads. Hence, one thread has to
wait, till the other thread gets executed. Therefore, this state is referred as waiting state.
5. Dead state: This is the state when the thread is terminated. The thread is in running state and as soon as
it completed processing it is in "dead state".
The program uses the following methods yield( ), sleep( ) and stop( ).
Program:
class A extends Thread
{
public void run ( )
{
for(int i=1; i<=20; i++)
{
if (i==3)
yield ( );
System.out.println(“From thread A: i= “+i);
}
}
}
class B extends Thread
{
public void run ( )
{
for (int j=1;j<=20;j++)
{
if (j==10)
stop ( );
System.out.println(“From thread B: j=”+j);
}
3
UNIT V
}
}
class C extends Thread
{
public void run ( )
{
for (int k=1;k<=20;k++)
{
try
{
sleep(1000);
}
catch (Exception e) { }
System.out.println(“From thread C: k=”+k);
}
}
}
class ThreadMethods
{
public static void main(String args[ ])
{
A p=new A( );
B q=new B( );
C r=new C( );
p.start( );
q.start( );
r.start( );
}
}
Creating threads
A new thread can be created in two ways.
1. By creating a thread class: Define a class that extends thread class and override its run() method with
the code required by the thread.
2. By converting a class to a thread(Using Runnable interface): Define a class that implements
Runnable interface. The Runnable interface has only one method, run( ), i.e., to be defined in the method
with the code to be executed by the thread.
I. EXTENDING THE THREAD CLASS
We can make our class runnable as thread by extending the class java.lang. Thread. This allows us to
access all the thread methods directly. It includes the following steps.
1. Declare the class as extending the Thread class.
2. Implement the run() method .
3. Create a thread object and call the start().
1. Declaring the thread class:
The thread can be extended as follows
class MyThread extends Thread
{
……….…….
……………..
} //Now we have a new type of thread MyThread.
2. Implementing the run ( ) method
The run ( ) method has been inherited by the class ‘MyThread’. We have to override this method in order to
implement the code to be executed by our thread. The basic implementation of run( ) is as follows
public void run()
{
…………..
………….. // Thread code here
4
UNIT V
}
When we start the new thread, java calls the threads run( ) method.
3. Starting New Thread:To create and run an instance of our thread class we must write the following.
MyThread aThread=new MyThread ( ); //Creation
aThread.start( ); //invokes run( ) method
The thread is also started by using the following statement.
new MyThread ( ).start( );
STOPPING AND BLOCKING A THREAD
Stopping a Thread
Whenever we want to stop a thread from running further, we may do by calling its stop( ) method.
aThread.stop( );
Here aThread is a thread object.
This statement causes the thread to move to the Dead state. A thread will also move to the dead state
automatically when it reaches the end of its method. The stop( ) method may be used when the thread is to
be stopped before its completion.
Blocking a thread
A thread can also be temporarily suspended (or) blocked from entering into the runnable and running state
by using the following thread methods.
sleep ( ) // blocked for a specified time.
suspend ( ) // blocked until further orders.
wait ( ) // blocked until certain conditions occur.
These methods cause the thread to go into the blocked state. The thread will return to the runnable
state when the specified time is elapsed in the case of sleep ( ), the resume ( ) method is invoked in the
case of suspend ( ), and the notify ( ) method is called in the case of wait( ) method.
5
UNIT V
NOTE
Can we start a thread twice (2m)
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is
thrown. In such case, thread will run once but for second time, it will throw exception.
What if we call run() method directly instead start() method(2m)
Each thread starts in a separate call stack.
Invoking the run() method from main thread, the run() method goes onto the current call
stack rather than at the beginning of a new call stack.
The join() method
The join() method waits for a thread to die. In other words, it causes the currently running threads to stop
executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Example of join() method
1. class TestJoinMethod1 extends Thread{
2. public void run(){
3. for(int i=1;i<=5;i++){
4. try{
5. Thread.sleep(500);
6. }catch(Exception e){System.out.println(e);}
7. System.out.println(i);
8. } }
9. public static void main(String args[]){
10. TestJoinMethod1 t1=new TestJoinMethod1();
11. TestJoinMethod1 t2=new TestJoinMethod1();
12. TestJoinMethod1 t3=new TestJoinMethod1();
6
UNIT V
13. t1.start();
14. try{
15. t1.join();
16. }catch(Exception e){System.out.println(e);}
17. t2.start();
18. t3.start();
19. } }
Thread Priority
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread
schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not
guaranteed because it depends on JVM specification that which scheduling it chooses.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY).
The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
7
UNIT V
6. public static void main(String args[]){
7. TestMultiPriority1 m1=new TestMultiPriority1();
8. TestMultiPriority1 m2=new TestMultiPriority1();
9. m1.setPriority(Thread.MIN_PRIORITY);
10. m2.setPriority(Thread.MAX_PRIORITY);
11. m1.start();
12. m2.start();
13. } }
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.
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
Why use Synchronization (2M)
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
Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1.1 Synchronized method.
1.2 Synchronized block.
1.3 static synchronization.
2. Cooperation (Inter-thread communication in java)
Understanding the problem without Synchronization (Generating 5th Table 10th Table )
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
1. class Table{
2. void printTable(int n){//method not synchronized
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
8
UNIT V
6. Thread.sleep(1000);
7. }catch(Exception e){System.out.println(e);}
8. } } }
9. class MyThread1 extends Thread{
10. Table t;
11. MyThread1(Table t){
12. this.t=t;
13. }
14. public void run(){
15. t.printTable(5);
16. } }
17. class MyThread2 extends Thread{
18. Table t;
19. MyThread2(Table t){
20. this.t=t;
21. }
Output: 5
22. public void run(){ 100
23. t.printTable(100); 10
24. } } 200
25. 15
26. class TestSynchronization1{ 300
27. public static void main(String args[]){ 20
400
28. Table obj = new Table();//only one object
25
29. MyThread1 t1=new MyThread1(obj);
500
30. MyThread2 t2=new MyThread2(obj);
31. t1.start();
32. t2.start();
33. } }
From the above output that both the 5th Table and 100th Table values are jumbles and messed with each
other, since “void printTable(int n)” is not synchronized .
Generating 5th Table 10th Table using synchronized Method
1. class Table{
2. synchronized void printTable(int n){//synchronized method
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. } } }
9. class MyThread1 extends Thread{ Output: 5
10. Table t; 10
11. MyThread1(Table t){ 15
12. this.t=t; 20
13. } 25
100
14. public void run(){
200
15. t.printTable(5); 300
16. } } 400
17. class MyThread2 extends Thread{ 500
18. Table t;
9
UNIT V
19. MyThread2(Table t){
20. this.t=t;
21. }
22. public void run(){
23. t.printTable(100);
24. } }
25. public class TestSynchronization2{
26. public static void main(String args[]){
27. Table obj = new Table();//only one object
28. MyThread1 t1=new MyThread1(obj);
29. MyThread2 t2=new MyThread2(obj);
30. t1.start();
31. t2.start();
32. } }
Now, the output is clear and printed one after another (5th Table then 100th Table)
2. Synchronized Block in Java
1. Synchronized block can be used to perform synchronization on any specific resource of the method.
2. Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you
can use synchronized block.
3. 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
1. synchronized (object reference expression) {
2. //code block
3. }
Example of synchronized block Let's see the simple example of synchronized block.
1. class Table{
2. void printTable(int n){ Output:5
3. synchronized(this){//synchronized block 10
4. for(int i=1;i<=5;i++){ 15
5. System.out.println(n*i); 20
6. try{ 25
100
7. Thread.sleep(400);
200
8. }catch(Exception e){System.out.println(e);}
300
9. } 400
10. } 500
11. }//end of the method
12. }
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
10
UNIT V
20. } }
21. class MyThread2 extends Thread{
22. Table t;
23. MyThread2(Table t){
24. this.t=t;
25. }
26. public void run(){
27. t.printTable(100);
28. } }
29.
30. public class TestSynchronizedBlock1{
31. public static void main(String args[]){
32. Table obj = new Table();//only one object
33. MyThread1 t1=new MyThread1(obj);
34. MyThread2 t2=new MyThread2(obj);
35. t1.start();
36. t2.start();
37. } }
11
UNIT V
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(long timeout)throws waits for the specified amount of time.
InterruptedException
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()
wait() method releases the lock sleep() method doesn't release the lock.
should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is
completed.
Example of inter thread communication in java (as withdraw– Consumer; Deposit- Producer)
Let's see the simple example of inter thread communication.
1. class Customer{
2. int amount=10000;
3. synchronized void withdraw(int amount){
4. System.out.println("going to withdraw...");
5. if(this.amount<amount){
6. System.out.println("Less balance; waiting for deposit...");
7. try{wait();}catch(Exception e){}
8. }
9. this.amount-=amount;
10. System.out.println("withdraw completed...");
11. }
12. synchronized void deposit(int amount){
13. System.out.println("going to deposit...");
14. this.amount+=amount;
15. System.out.println("deposit completed... ");
12
UNIT V
16. notify();
17. }
18. }
19. class Test{
20. public static void main(String args[]){
21. final Customer c=new Customer();
22. new Thread(){ This is called “anonymous calling” ,
23. public void run(){c.withdraw(15000);} i.e without creating an object.
24. }.start();
25.
26. new Thread(){
27. public void run(){c.deposit(10000);}
28. }.start();
29. }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
13
UNIT V
StringTokenizer
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break
string.
Constructors of StringTokenizer class
Constructor Description
StringTokenizer(String str, String delim) creates StringTokenizer with specified string and delimeter.
StringTokenizer(String str, String delim, creates StringTokenizer with specified string, delimeter and
boolean returnValue) returnValue. If return value is true, delimiter characters are
considered to be tokens. If it is false, delimiter characters
serve to separate tokens.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
1. import java.util.*;
2. public class Test {
3. public static void main(String[] args) {
4. StringTokenizer st = new StringTokenizer("my,name,is,SURESH BABU");
5. // printing next token
6. System.out.println("Next token is : " + st.nextToken(","));
7. } }
Date and Time
The following packages contains classes for representing date and time.
java.time,
java.util,
java.sql and
java.text
Java has introduced a new Date and Time API since Java 8.
java.util.Date
The java.util.Date class represents date and time in java.
It provides constructors and methods to deal with date and time in java.
It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.
14
UNIT V
After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.
java.util.Date Constructors
No Constructor Description
.
2) Date(long milliseconds) Creates a date object for the given milliseconds since January 1, 1970,
00:00:00 GMT.
java.util.Date Methods
No. Method Description
1) boolean after(Date date) tests if current date is after the given date.
2) boolean before(Date date) tests if current date is before the given date.
5) boolean equals(Date date) compares current date with given date for equality.
6) static Date from(Instant instant) returns an instance of Date object from Instant date.
8) int hashCode() returns the hash code value for this date object.
9) void setTime(long time) changes the current date and time to given time.
java.util.Date Example
1. public class UtilDateExample1{
2. public static void main(String args[]){
3. java.util.Date date=new java.util.Date(); Output
4. System.out.println(date); Tue Feb 16 10:12:02 IST 2021
Tue Feb 16 10:12:02 IST 2021
5. long millis=System.currentTimeMillis();
6. java.util.Date date1=new java.util.Date(millis);
7. System.out.println(date);
8. }}
java.sql.Date
The java.sql.Date class represents only date in java. It inherits java.util.Date class.
The java.sql.Date instance is widely used in JDBC because it represents the date that can be stored
in database.
java.sql.Date Constructor
No Constructor Description
.
15
UNIT V
1) Date(long Creates a sql date object for the given milliseconds since January 1, 1970,
milliseconds) 00:00:00 GMT.
java.sql.Date Methods
No. Method Description
1) void setTime(long time) changes the current sql date to given time.
5) static Date valueOf(LocalDate date) returns sql date object for the given LocalDate.
6) static Date valueOf(String date) returns sql date object for the given String.
Calendar Class
Java Calendar class is an abstract class that provides methods for converting date between a specific instant
in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and
implements the Comparable interface.
Example
1. import java.util.Calendar;
2. public class CalendarExample1 {
3. public static void main(String[] args) {
4. Calendar calendar = Calendar.getInstance();
5. System.out.println("The current date is : " + calendar.getTime());
6. calendar.add(Calendar.DATE, -15);
7. System.out.println("15 days ago: " + calendar.getTime()); OUTPUT
The current date is : Tue Feb 16 10:17:39 IST 2021
8. calendar.add(Calendar.MONTH, 4); 15 days ago: Mon Feb 01 10:17:39 IST 2021
9. System.out.println("4 months later: " + calendar.getTime()); 4 months later: Tue Jun 01 10:17:39 IST 2021
10. calendar.add(Calendar.YEAR, 2); 2 years later: Thu Jun 01 10:17:39 IST 202
11. System.out.println("2 years later: " + calendar.getTime());
12. }
13. }
No Method Description
1. public void add(int field, int amount) Adds the specified (signed) amount of time to the
given calendar field.
16
UNIT V
2. public boolean after (Object when) The method Returns true if the time represented by
this Calendar is after the time represented by when
Object.
3. public boolean before(Object when) The method Returns true if the time represented by
this Calendar is before the time represented by when
Object.
4. public final void clear(int field) Set the given calendar field value and the time value
of this Calendar undefined.
5. public Object clone() Clone method provides the copy of the current object.
6. public boolean equals(Object object) The equals() method compares two objects for
equality and Returns true if they are equal.
7. public static Calendar getInstance() This method is used with calendar object to get the
instance of calendar according to current time zone
set by java runtime environment
8. public final Date getTime() This method gets the time value of calendar object
and Returns date.
9. public void set(int field, int value) Sets the specified calendar field by the specified
value.
10. public final void setTime(Date date) Sets the Time of current calendar object. A Date
object id passed as the parameter.
Random class
Random class is used to generate pseudo-random numbers in java.
An instance of this class is thread-safe. This class provides various method calls to generate different
random data types such as float, double, int.
Constructors:
Random(): Creates a new random number generator
Random(long seed): Creates a new random number generator using a single long seed
17
UNIT V
12. System.out.println(random.nextFloat());
13. System.out.println(random.nextGaussian());
14. byte[] bytes = new byte[10];
15. random.nextBytes(bytes);
16. System.out.printf("[");
17. for(int i = 0; i< bytes.length; i++)
18. {
19. System.out.printf("%d ", bytes[i]);
20. }
21. System.out.printf("]\n");
22. System.out.println(random.nextLong());
23. System.out.println(random.nextInt());
24. }}
Formatter class
The java.util.Formatter class provides support for layout justification and alignment, common formats for
numeric, string, and date/time data, and locale-specific output.
Following are the important points about Formatter –
Important Format Specifiers
Format Example & Output
Description
Specifier
Space When creating columns of numbers, it is formatter.format("% d", -111);
sometimes very useful to print a space before a Output:
positive number so that positive and negative -111
number get aligned. To do this, space format
specifier can be used.
+ Sign This adds the + sign before positive numeric Formatter().format("%+d", 111);
value, and has no effect on negative numeric Output:
value. +111
18
UNIT V
import java.util.Formatter;
public class GFG {
public static void main(String args[])
{
// Create the Formatter instance
Formatter formatter = new Formatter();
formatter = new Formatter();
formatter.format("%16.2e", 123.1234567);
System.out.println("Scientific notation to 2 places: " + formatter);
// Format 4 decimal places.
formatter = new Formatter();
formatter.format("%.4f", 123.1234567);
System.out.println("Decimal floating-point" + " notation to 4 places: " + formatter);
// Format 4 places.
// The %g format specifier causes Formatter
// to use either %f or %e, whichever is shorter
formatter = new Formatter();
formatter.format("%.4g", 123.1234567);
System.out.println("Scientific or Decimal floating-point "+ "notation to 4 places: " +
formatter);
// Display at most 15 characters in a string.
formatter = new Formatter();
formatter.format("%.15s", "12345678901234567890");
19
UNIT V
Output:
Scientific notation to 2 places: 1.23e+02
Decimal floating-point notation to 4 places: 123.1235
Scientific or Decimal floating-point notation to 4 places: 123.1
String notation to 15 places: 123456789012345
value in 10 digits: 0000000088
Scanner Class
1. The scanner class is a class in java.util, which allows the user to read values of various types.
2. A scanner object can read user input entered on the console or from a file.
3. A scanner breaks its input into separate tokens and returns them at a time.
4. The scanner provides methods to convert the tokens into values of different types.
5. A Scanner is not safe for multithreaded use without external synchronization.
Syntax:
Scanner s=new Scanner(System.in);
int i = s.nextInt( );
We can create scanners in two ways
1. To read from the console
Scanner s = new Scanner(System.in);
2. To read from a file
Scanner s = new Scanner(new FileStream(“filename.txt”));
Constructors:
Scanner(File source)
Constructs a new Scanner that produces values scanned from the specified file.
Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream.
Scanner(String source)
Constructs a new Scanner that produces values scanned from the specified string.
Scanner Methods :
Scanner Method Description
nextInt( ) Reads and converts next token to a integer value
nextLong( ) Reads and converts next token to a long value
nextDouble( ) Reads and converts next token to a double value
nextString( ) Reads a String
(or) next()
nextBoolean( ) Reads and converts next token to a boolean value
Java-Stream Classes
20
UNIT V
In Java, a stream is a path along which the data flows. Every stream has a source and a destination. We can
build a complex file processing sequence using a series of simple stream operations.
Types of Streams
The java.io package contains a large number of stream classes that provide capabilities for processing all
types of data. These classes may be categorized into two groups based on the data type on which they
operate.
DataOutputStream An output stream that contain method for writing java standard data type
22
UNIT V
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOStreamsExample {
public static void main(String args[]) throws IOException {
//Creating FileInputStream object
File file = new File("D:/myFile.txt");
FileInputStream fis = new FileInputStream(file);
byte bytes[] = new byte[(int) file.length()];
//Reading data from the file
fis.read(bytes);
//Writing data to another file
File out = new File("D:/CopyOfmyFile.txt");
FileOutputStream outputStream = new FileOutputStream(out);
//Writing data to the file
outputStream.write(bytes);
outputStream.flush();
System.out.println("Data successfully written in the specified file");
}
}
Output
Data successfully written in the specified file
Character Stream Classes
Character streams can be used to read and write 16-bit Unicode characters. Like byte streams, there are two
kinds of character stream classes, namely, reader stream classes and writer stream classes.
23
UNIT V
These two abstract classes have several concrete classes that handle unicode character.
}
Output
Data successfully written in the specified file
In Java, there are three different ways for reading input from the user in the command line environment
(console).
1.Using Buffered Reader Class
This is the Java classical method to take input, Introduced in JDK1.0.
This method is used by wrapping the System.in (standard input stream) in an InputStreamReader
which is wrapped in a BufferedReader, we can read input from the user in the command line.
Advantages
The input is buffered for efficient reading.
Drawback:
The wrapping code is hard to remember.
Program:
Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
Regular expressions can be used to find tokens.
25
UNIT V
Drawback:
The reading methods are not synchronized
26
UNIT V
reader()
The basic differences between print() and println() methods is that print() method displays the
string in the same line whereas println() method outputs a newline character after its execution.
27
UNIT V
1. class writeEg
2. {
3. public static void main(String args[])
4. {
5. int a, b;
6. a = 'Q';
7. b = 65;
8. System.out.write(a);
9. System.out.write('\n');
10. System.out.write(b);
11. System.out.write('\n');
12. }
13. }
File(File parent, String child) It creates a new File instance from a parent abstract pathname and a
child pathname string.
File(String pathname) It creates a new File instance by converting the given pathname string
into an abstract pathname.
File(String parent, String It creates a new File instance from a parent pathname string and a child
child) pathname string.
File(URI uri) It creates a new File instance by converting the given file: URI into an
abstract pathname.
Useful Methods
Method Description
createNewFile() It atomically creates a new, empty file named by this abstract pathname
if and only if a file with this name does not yet exist.
canWrite() It tests whether the application can modify the file denoted by this
abstract pathname.String[]
canExecute() It tests whether the application can execute the file denoted by this
abstract pathname.
canRead() It tests whether the application can read the file denoted by this abstract
pathname.
isDirectory() It tests whether the file denoted by this abstract pathname is a directory.
isFile() It tests whether the file denoted by this abstract pathname is a normal
file.
28
UNIT V
getName() It returns the name of the file or directory denoted by this abstract
pathname.
getParent() It returns the pathname string of this abstract pathname's parent, or null
if this pathname does not name a parent directory.
getFreeSpace() It returns the number of unallocated bytes in the partition named by this
abstract path name.
list(FilenameFilter filter) It returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname that satisfy the specified
filter.
1. import java.io.*;
2. public class FileDemo {
3. public static void main(String[] args) {
4.
5. try {
6. File file = new File("javaFile123.txt");
7. if (file.createNewFile()) {
8. System.out.println("New File is created!");
9. } else {
10. System.out.println("File already exists.");
11. }
12. } catch (IOException e) {
13. e.printStackTrace();
14. }
15.
16. }
17. }
1. import java.io.*;
2. public class FileDemo2 {
3. public static void main(String[] args) {
4.
5. String path = "";
6. boolean bool = false;
7. try {
29
UNIT V
8. // createing new files
9. File file = new File("testFile1.txt");
10. file.createNewFile();
11. System.out.println(file);
12. // createing new canonical from file object
13. File file2 = file.getCanonicalFile();
14. // returns true if the file exists
15. System.out.println(file2);
16. bool = file2.exists();
17. // returns absolute pathname
18. path = file2.getAbsolutePath();
19. System.out.println(bool);
20. // if file exists
21. if (bool) {
22. // prints
23. System.out.print(path + " Exists? " + bool);
24. }
25. } catch (Exception e) {
26. // if any error occurs
27. e.printStackTrace();
28. }
29. }
30. }
Java File Example 3
1. import java.io.*;
2. public class FileExample {
3. public static void main(String[] args) {
4. File f=new File("/Users/NECG/Documents");
5. String filenames[]=f.list();
6. for(String filename:filenames){
7. System.out.println(filename);
8. }
9. }
10. }
1. import java.io.*;
2. public class FileExample {
3. public static void main(String[] args) {
4. File dir=new File("/Users/NECG/Documents");
5. File files[]=dir.listFiles();
6. for(File file:files){
7. System.out.println(file.getName()+" Can Write: "+file.canWrite()+"
8. Is Hidden: "+file.isHidden()+" Length: "+file.length()+" bytes");
9. }
10. }
11. }
30
UNIT V
Java - RandomAccessFile
RandomAccessFile class is used for reading and writing to random access file.
A random access file behaves like a large array of bytes. There is a cursor implied to the array
called file pointer, by moving the cursor we do the read write operations.
If end-of-file is reached before the desired number of byte has been read than EOFException
is thrown.
Constructor
Constructor Description
RandomAccessFile(File file, String mode) Creates a random access file stream to read from, and
optionally to write to, the file specified by the File
argument.
RandomAccessFile(String name, String mode) Creates a random access file stream to read from, and
optionally to write to, a file with the specified name.
Example
1. import java.io.IOException;
2. import java.io.RandomAccessFile;
3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }
31
UNIT V
The myFile.TXT contains text "This class is used for reading and writing to random access file."
*****END*****
32