allizwell.jobsdoor360.in

File Handling and Multithreading

Java Programming Course › Module 09: File Handling and Multithreading
JAVA PROGRAMMING / MODULE 09

File Handling and Multithreading

Learn how to create, read, write and manage files in Java. Also understand threads, multithreading, thread life cycle and synchronization using simple examples.

Beginner Friendly Placement Preparation 8 Topics

Introduction to This Module

Until now, most of the Java programs you have written display results on the screen. But real-world applications often need to store information permanently, read saved data and perform multiple tasks efficiently.

Java provides file handling features to work with files and folders. It also provides multithreading, which allows multiple tasks to make progress concurrently.

In this module, you will learn both concepts step by step using simple Java programs.

What You Will Learn

  • Understand why file handling is needed.
  • Read text files using Java classes.
  • Create files and write data into them.
  • Append new data without removing existing content.
  • Perform basic file operations using the File class.
  • Understand threads and multithreading.
  • Create threads using Thread and Runnable.
  • Understand thread life cycle and common thread methods.
  • Learn synchronization and why it is important.
TOPIC 01

1. Introduction to File Handling

What Is File Handling?

File handling means creating, reading, writing, updating and managing files using a program.

Normally, when a Java program runs, its variables and temporary data are stored in memory. When the program stops, that temporary data is lost.

If we want to save information so that it can be used later, we can store it in a file.

Real-Life Example

Imagine a school management system. It stores student names, roll numbers and marks.

If all this information disappeared whenever the application was closed, it would be very inconvenient. The application can save the information in files so it can be accessed later.

Why Do We Need File Handling?

  • To store information permanently.
  • To read previously saved information.
  • To update or add information.
  • To maintain records such as student details and bills.
  • To exchange information between programs.

Common File Operations

Operation Meaning
Create Create a new file.
Read Get information from a file.
Write Store information in a file.
Append Add information at the end of an existing file.
Delete Remove a file.

Important Java Classes for File Handling

Class Purpose
File Represents a file or directory path and provides file-related operations.
FileWriter Writes character data into a file.
FileReader Reads character data from a file.
BufferedReader Reads text efficiently, including line by line.
BufferedWriter Writes text efficiently using buffering.
Scanner Can read text and tokens from a file.
Remember: File handling allows a program to store and retrieve data even after the program has finished running.
TOPIC 02

2. Reading Files in Java

What Does Reading a File Mean?

Reading a file means retrieving information that has already been stored in a file.

Java provides different classes for reading text files. In this lesson, we will use FileReader and BufferedReader.

Method 1: Reading Using FileReader

FileReader is used to read character data from a text file. Its read() method reads one character at a time.

Suppose a file named message.txt contains:

message.txt
Hello Java
Welcome to File Handling

Java Program

Java Code
import java.io.FileReader;
import java.io.IOException;

class Main {

    public static void main(String[] args) {

        try (FileReader reader =
                 new FileReader("message.txt")) {

            int character;

            while ((character = reader.read()) != -1) {

                System.out.print((char) character);

            }

        } catch (IOException e) {

            System.out.println("File reading error: " + e.getMessage());

        }
    }
}
Output:
Hello Java
Welcome to File Handling

Understanding the Program

  • FileReader opens the file for reading.
  • read() reads one character at a time.
  • It returns -1 when the end of the file is reached.
  • (char) character converts the read value into a character.
  • The try-with-resources statement automatically closes the reader.

Method 2: Reading Using BufferedReader

BufferedReader makes reading text more convenient and efficient. Its readLine() method reads one complete line at a time.

Java Code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Main {

    public static void main(String[] args) {

        try (BufferedReader reader =
                 new BufferedReader(
                     new FileReader("message.txt"))) {

            String line;

            while ((line = reader.readLine()) != null) {

                System.out.println(line);

            }

        } catch (IOException e) {

            System.out.println("Error: " + e.getMessage());

        }
    }
}
Output:
Hello Java
Welcome to File Handling

Difference Between FileReader and BufferedReader

FileReader BufferedReader
Reads character data. Reads text efficiently using a buffer.
Can read one character at a time. Can read a complete line using readLine().
Does not provide readLine(). Provides readLine().
Important: The file must exist at the specified path. Otherwise, Java may throw a FileNotFoundException.
TOPIC 03

3. Writing and Appending to Files

Writing Data into a File

Writing means storing information inside a file. Java provides FileWriter to write character data into text files.

Example: Writing into a File

Java Code
import java.io.FileWriter;
import java.io.IOException;

class Main {

    public static void main(String[] args) {

        try (FileWriter writer =
                 new FileWriter("student.txt")) {

            writer.write("Name: Aman");
            writer.write("\nMarks: 90");

            System.out.println("Data written successfully");

        } catch (IOException e) {

            System.out.println("Error: " + e.getMessage());

        }
    }
}
Console Output:
Data written successfully

Contents of student.txt:

student.txt
Name: Aman
Marks: 90

If the file does not exist, FileWriter normally creates it. If it already exists, the default constructor replaces its previous contents.

What Is Appending?

Appending means adding new information at the end of an existing file without removing its previous content.

Example: Appending Data

Java Code
import java.io.FileWriter;
import java.io.IOException;

class Main {

    public static void main(String[] args) {

        try (FileWriter writer =
                 new FileWriter("student.txt", true)) {

            writer.write("\nGrade: A");

            System.out.println("Data appended successfully");

        } catch (IOException e) {

            System.out.println("Error: " + e.getMessage());

        }
    }
}
Console Output:
Data appended successfully

Updated contents of student.txt:

student.txt
Name: Aman
Marks: 90
Grade: A

Difference Between Writing and Appending

Writing Appending
Normally replaces existing content. Preserves existing content.
Uses new FileWriter("file.txt"). Uses new FileWriter("file.txt", true).
Useful when creating or replacing file contents. Useful when adding new records.
Remember: In FileWriter, the second argument true enables append mode. The default is false.
TOPIC 04

4. File Class and File Operations

What Is the File Class?

The File class belongs to the java.io package. It represents a file or directory path.

It provides methods to check whether a file exists, create a new file, delete a file and get information about a file.

Creating a File

Java Code
import java.io.File;
import java.io.IOException;

class Main {

    public static void main(String[] args) {

        try {

            File file = new File("demo.txt");

            if (file.createNewFile()) {

                System.out.println("File created successfully");

            } else {

                System.out.println("File already exists");

            }

        } catch (IOException e) {

            System.out.println("An error occurred");

        }
    }
}
Possible Output:
File created successfully

The output depends on whether demo.txt already exists at the specified location.

Checking Whether a File Exists

Java Code
import java.io.File;

class Main {

    public static void main(String[] args) {

        File file = new File("demo.txt");

        if (file.exists()) {

            System.out.println("File exists");

        } else {

            System.out.println("File does not exist");

        }
    }
}
Possible Output:
File exists

Useful Methods of the File Class

Method Purpose
exists() Checks whether the path exists.
createNewFile() Creates a new empty file if it does not exist.
delete() Attempts to delete the file or empty directory.
getName() Returns the name of the file or directory.
getAbsolutePath() Returns the absolute path.
length() Returns the file size in bytes.
isFile() Checks whether the path represents a file.
isDirectory() Checks whether the path represents a directory.

Example: Getting File Information

Java Code
import java.io.File;

class Main {

    public static void main(String[] args) {

        File file = new File("demo.txt");

        if (file.exists()) {

            System.out.println("Name: " + file.getName());

            System.out.println("Path: " + file.getAbsolutePath());

            System.out.println("Size: " + file.length());

            System.out.println("Is file: " + file.isFile());

        } else {

            System.out.println("File not found");

        }
    }
}

The exact path and file size depend on your computer and the file contents.

Important: The File class represents a path. It does not itself read or write file contents. Use classes such as FileReader and FileWriter for that.
TOPIC 05

5. Introduction to Multithreading

What Is a Thread?

A thread is a small unit of execution within a program. It represents a path of work that the program can perform.

Every Java application starts with at least one thread, called the main thread.

What Is Multithreading?

Multithreading means using multiple threads within one program so that different tasks can make progress concurrently.

Real-Life Example

Imagine using a music application. While music is playing, the application may also download a song and update the screen.

If all these tasks had to wait for one another, the application could feel slow. Multithreading helps applications handle different tasks more effectively.

Single Thread vs Multithreading

Single Thread Multithreading
One thread performs the work. Multiple threads can perform work concurrently.
Tasks may need to wait for earlier tasks. Independent tasks can make progress without waiting for one another.
Suitable for simpler tasks. Useful for applications with multiple activities.

Advantages of Multithreading

  • Helps applications perform multiple tasks concurrently.
  • Can improve responsiveness.
  • Can make better use of available processor cores.
  • Is useful in games, servers and background processing.

Example: Main Thread

Java Code
class Main {

    public static void main(String[] args) {

        System.out.println("Hello from Java");

        System.out.println(
            "Thread name: " +
            Thread.currentThread().getName()
        );

    }
}
Output:
Hello from Java
Thread name: main

The Thread.currentThread() method returns the currently executing thread. Its getName() method returns the thread name.

Remember: Concurrency means tasks can make progress during overlapping periods. It does not always mean that they execute at the exact same time.
TOPIC 06

6. Creating Threads in Java

How Can We Create a Thread?

Java provides two commonly taught ways to create and run a thread:

  1. Extending the Thread class.
  2. Implementing the Runnable interface.

Method 1: Extending the Thread Class

We can create a class that extends Thread and overrides its run() method. The code inside run() defines the task performed by the thread.

Java Code
class MyThread extends Thread {

    public void run() {

        System.out.println("Thread is running");

    }
}

class Main {

    public static void main(String[] args) {

        MyThread t = new MyThread();

        t.start();

    }
}
Output:
Thread is running

Understanding the Program

  • MyThread extends the Thread class.
  • run() contains the task to be executed.
  • An object of MyThread is created.
  • start() starts a new thread.
  • The new thread executes the run() method.

Method 2: Implementing the Runnable Interface

We can also create a class that implements Runnable. This is often preferred because Java classes can extend only one class, but they can implement multiple interfaces.

Java Code
class MyTask implements Runnable {

    public void run() {

        System.out.println("Runnable thread is running");

    }
}

class Main {

    public static void main(String[] args) {

        MyTask task = new MyTask();

        Thread t = new Thread(task);

        t.start();

    }
}
Output:
Runnable thread is running

Method 3: Using a Lambda Expression

Runnable is a functional interface, so we can use a lambda expression to create its implementation.

Java Code
class Main {

    public static void main(String[] args) {

        Runnable task = () -> {

            System.out.println("Thread created using lambda");

        };

        Thread t = new Thread(task);

        t.start();

    }
}
Output:
Thread created using lambda

Difference Between Thread and Runnable

Thread Class Runnable Interface
Class extends Thread. Class implements Runnable.
Cannot extend another class at the same time. Can extend another class and implement Runnable.
Task and thread are combined in the class. Task is separate from the Thread object.

Important Difference Between start() and run()

This is a frequently asked interview question.

start() run()
Starts a new thread. Contains the task code executed by a thread.
The JVM schedules the new thread. A direct method call runs like an ordinary method call.
Can be called only once on a particular Thread object. Can be called directly like a normal method, but this does not start a new thread.
Placement Tip: To actually start a new thread, call start(), not just run().
TOPIC 07

7. Thread Life Cycle and Methods

What Is the Thread Life Cycle?

A thread does not remain in the same state throughout its execution. It moves through different states depending on what it is doing.

Official Thread States in Java

State Meaning
NEW A thread object has been created, but start() has not been called.
RUNNABLE The thread is ready to run or is running.
BLOCKED The thread is waiting to acquire a monitor lock.
WAITING The thread is waiting indefinitely for another thread to perform an action.
TIMED_WAITING The thread is waiting for a specified period.
TERMINATED The thread has finished execution.

Simple Thread Life Cycle Example

Java Code
class MyThread extends Thread {

    public void run() {

        System.out.println("Thread is running");

    }
}

class Main {

    public static void main(String[] args) {

        MyThread t = new MyThread();

        System.out.println(t.getState());

        t.start();

        try {

            t.join();

        } catch (InterruptedException e) {

            Thread.currentThread().interrupt();

        }

        System.out.println(t.getState());

    }
}
Output:
NEW
Thread is running
TERMINATED

The first state is NEW because the thread has not started. After start(), it becomes runnable. Once its task finishes, it reaches TERMINATED.

Important Thread Methods

Method Purpose
start() Starts a new thread.
run() Contains the thread's task.
sleep() Pauses the current thread for a specified time.
join() Waits for another thread to finish.
getName() Returns the thread's name.
setName() Changes the thread's name.
currentThread() Returns the currently executing thread.
isAlive() Checks whether a thread has started and has not yet terminated.

Example 1: Using sleep()

The sleep() method pauses the currently executing thread for a specified amount of time.

Java Code
class Main {

    public static void main(String[] args) {

        for (int i = 1; i <= 3; i++) {

            System.out.println(i);

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                Thread.currentThread().interrupt();

                break;

            }
        }
    }
}
Output:
1
2
3

Each number is displayed with approximately one second between successive iterations.

Example 2: Using join()

The join() method makes one thread wait until another thread finishes.

Java Code
class MyThread extends Thread {

    public void run() {

        System.out.println("Child thread running");

    }
}

class Main {

    public static void main(String[] args) {

        MyThread t = new MyThread();

        t.start();

        try {

            t.join();

        } catch (InterruptedException e) {

            Thread.currentThread().interrupt();

        }

        System.out.println("Main thread continues");

    }
}
Output:
Child thread running
Main thread continues

Example 3: Thread Names

Java Code
class Main {

    public static void main(String[] args) {

        Thread t = Thread.currentThread();

        System.out.println(t.getName());

        t.setName("MyMainThread");

        System.out.println(t.getName());

    }
}
Output:
main
MyMainThread
Remember: sleep() pauses the current thread. join() waits for another thread to finish. Both methods can throw InterruptedException.
TOPIC 08

8. Synchronization and Thread Safety

What Is Synchronization?

Synchronization is a technique used to control access to shared resources when multiple threads are working with the same data.

It helps prevent threads from interfering with one another when they update shared information.

Real-Life Example

Imagine two people trying to update the same bank account balance at the same time.

If both people read the old balance and then update it independently, one update might overwrite the other. This can produce an incorrect result.

Synchronization helps control access so that conflicting updates do not happen together.

What Is a Race Condition?

A race condition occurs when the result of a program depends on the timing or order in which multiple threads access shared data.

Example Without Synchronization

Java Code
class Counter {

    int count = 0;

    void increment() {

        count++;

    }
}

class MyThread extends Thread {

    Counter counter;

    MyThread(Counter counter) {

        this.counter = counter;

    }

    public void run() {

        for (int i = 0; i < 1000; i++) {

            counter.increment();

        }
    }
}

class Main {

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

        Counter counter = new Counter();

        MyThread t1 = new MyThread(counter);

        MyThread t2 = new MyThread(counter);

        t1.start();

        t2.start();

        t1.join();

        t2.join();

        System.out.println(counter.count);

    }
}
Important: The expected result is 2000, but this program may print a smaller value because count++ is not an atomic operation. The exact incorrect result is not predictable.

Using synchronized to Solve the Problem

The synchronized keyword allows only one thread at a time to execute a synchronized method or block protected by the same monitor lock.

Java Code
class Counter {

    int count = 0;

    synchronized void increment() {

        count++;

    }
}

class MyThread extends Thread {

    Counter counter;

    MyThread(Counter counter) {

        this.counter = counter;

    }

    public void run() {

        for (int i = 0; i < 1000; i++) {

            counter.increment();

        }
    }
}

class Main {

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

        Counter counter = new Counter();

        MyThread t1 = new MyThread(counter);

        MyThread t2 = new MyThread(counter);

        t1.start();

        t2.start();

        t1.join();

        t2.join();

        System.out.println(counter.count);

    }
}
Output:
2000

How Does Synchronization Work?

  • Both threads share the same Counter object.
  • The increment() method is marked synchronized.
  • A thread must acquire the object's monitor lock before entering the method.
  • Other threads using the same lock must wait until it is released.
  • This protects the shared counter from conflicting updates.

What Is Thread Safety?

Thread safety means that code behaves correctly when accessed by multiple threads at the same time.

Important Terms

Term Meaning
Race Condition A problem caused by unpredictable timing of access to shared data.
Synchronization Controls access to shared resources using locks.
Thread Safety Correct behaviour when code is used by multiple threads.
Shared Resource Data or an object accessed by multiple threads.
Placement Tip: Remember that synchronization is used to protect shared data. The synchronized keyword helps prevent race conditions when multiple threads access the same protected resource.

Important Interview Questions

Q1. What is file handling in Java?

File handling means creating, reading, writing, updating and managing files using Java programs.

Q2. Which package contains Java file handling classes?

Many traditional file handling classes, such as File, FileReader and FileWriter, are available in the java.io package.

Q3. What is the use of the File class?

The File class represents a file or directory path and provides methods to check, create and delete files and obtain file information.

Q4. What is the difference between FileReader and BufferedReader?

FileReader reads character data, while BufferedReader reads text efficiently and provides readLine() to read complete lines.

Q5. What is the difference between write and append?

Writing with the default FileWriter constructor replaces existing content. Appending adds new content at the end of the file.

Q6. How do you enable append mode in FileWriter?

Use the constructor new FileWriter("file.txt", true).

Q7. What is a thread in Java?

A thread is a unit of execution within a program that performs a particular task.

Q8. What is multithreading?

Multithreading allows multiple threads to make progress concurrently within one program.

Q9. What are the two common ways to create a thread?

By extending the Thread class or implementing the Runnable interface.

Q10. What is the difference between start() and run()?

start() starts a new thread, while a direct call to run() executes it like a normal method call.

Q11. What is the main thread?

The main thread is the thread that begins executing a Java program through its main() method.

Q12. Name the six official Java thread states.

NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED.

Q13. What is the use of sleep()?

sleep() pauses the currently executing thread for a specified period.

Q14. What is the use of join()?

join() makes the current thread wait until another thread finishes.

Q15. What is synchronization?

Synchronization controls access to shared resources so that conflicting operations do not execute simultaneously under the same lock.

Q16. What is a race condition?

A race condition occurs when the result depends on the unpredictable timing or order of multiple threads accessing shared data.

Q17. What is thread safety?

Thread safety means that code continues to behave correctly when accessed by multiple threads.

Q18. What is the use of the synchronized keyword?

It provides locking so that only one thread at a time can execute a synchronized method or block using the same monitor.

Module Summary

  • File handling allows Java programs to store and retrieve information.
  • FileReader reads character data from text files.
  • BufferedReader can read text line by line.
  • FileWriter writes and appends text to files.
  • The File class represents file and directory paths.
  • A thread is a unit of execution within a program.
  • Multithreading allows multiple tasks to make progress concurrently.
  • Threads can be created using Thread or Runnable.
  • start() starts a new thread, while run() contains its task.
  • Java defines six official thread states.
  • sleep() pauses the current thread and join() waits for another thread.
  • Synchronization helps protect shared data from conflicting updates.

Practice Questions

Try these programs yourself to improve your understanding of file handling and multithreading.

  1. Write a program to create a text file using the File class.
  2. Write a program to check whether a file exists.
  3. Write a program to display the name and size of a file.
  4. Write a program to write your name and age into a file.
  5. Write a program to append new text to an existing file.
  6. Write a program to read a file using FileReader.
  7. Write a program to read a file line by line using BufferedReader.
  8. Create a thread by extending the Thread class.
  9. Create a thread by implementing Runnable.
  10. Create a thread using a lambda expression.
  11. Write a program to display the current thread name.
  12. Write a program that uses sleep() to pause execution.
  13. Write a program that uses join() to wait for another thread.
  14. Create two threads that print numbers from 1 to 5.
  15. Create a shared counter and update it using synchronized.

Congratulations! Module 09 Completed

You have learned how to work with files in Java and how to create and manage threads. You also understand thread states, important thread methods, synchronization and thread safety.

Practise the programs in this module before moving to the final module of your Java placement preparation course.

Scroll to Top