File Handling Using Thread in Java

Published: 08 May 2024
on channel: Anindita Das Bhattacharjee
696
78

import java.io.FileWriter;
import java.io.IOException;

These lines import necessary classes from the java.io package. FileWriter is used to write characters to a file, and IOException is an exception that might be thrown during input-output operations.

class NumberWriter extends Thread {

Defines a new class named NumberWriter which extends the Thread class. This suggests that instances of NumberWriter can be executed concurrently.

private final int startNumber;
private final int endNumber;
private final String fileName;

Declares three private instance variables: startNumber, endNumber, and fileName. These variables will hold the starting and ending numbers for the range of numbers to be written, and the filename to which these numbers will be written.

public void run() {

This method overrides the run() method defined in the Thread class. It is the entry point for the concurrent execution of this thread.

try {
FileWriter writer = new FileWriter(fileName);

Creates a new FileWriter object with the specified fileName. This object will be used to write data to the file.

public class Main {
public static void main(String[] args) {
NumberWriter oddWriter = new NumberWriter(1, 150, "odd_numbers.txt");
NumberWriter evenWriter = new NumberWriter(2, 150, "even_numbers.txt");

In the Main class, two instances of NumberWriter are created: oddWriter to write odd numbers and evenWriter to write even numbers. Each instance is initialized with appropriate start and end numbers along with the filename.

oddWriter.start();
evenWriter.start();

Starts the execution of both oddWriter and evenWriter threads concurrently.

try {
oddWriter.join();
evenWriter.join();

The main thread (represented by main()) waits for both oddWriter and evenWriter threads to finish executing using the join() method. This ensures that the message "Numbers written successfully." is printed only after both threads have completed their execution.

System.out.println("Numbers written successfully.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Prints a message indicating that numbers have been successfully written to the files once both threads have completed. Also, catches and prints any InterruptedException that might occur during the waiting process.


On this page of the site you can watch the video online File Handling Using Thread in Java with a duration of hours minute second in good quality, which was uploaded by the user Anindita Das Bhattacharjee 08 May 2024, share the link with friends and acquaintances, this video has already been watched 696 times on youtube and it was liked by 78 viewers. Enjoy your viewing!