0% found this document useful (0 votes)
4 views9 pages

Oopex 9

The document outlines a Java program focused on file handling using multithreading to manage large datasets. It details key components such as the File class and input/output streams, along with common operations like creating, reading, writing, renaming, and deleting files. Additionally, it includes example code for creating a profile file and a menu-driven application for various file operations.

Uploaded by

isaacbenjamin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Oopex 9

The document outlines a Java program focused on file handling using multithreading to manage large datasets. It details key components such as the File class and input/output streams, along with common operations like creating, reading, writing, renaming, and deleting files. Additionally, it includes example code for creating a profile file and a menu-driven application for various file operations.

Uploaded by

isaacbenjamin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Ex. No.

9 FILE HANDLING

18/10//24 URK23AI1035

Aim :

To design and implement a comprehensive Java program that effectively utilizes multithreading
concepts to manage, process, and analyze large datasets containing record information, thereby
improving overall performance and efficiency

Description :
File handling in Java is accomplished through a set of classes and interfaces
provided in the java.io and java.nio.file packages. These tools enable
developers to interact with the file system, perform operations such as creating,
reading, writing, renaming, and deleting files and directories, as well as managing file
permissions and attributes.
Key Components of File Handling in Java:

1. File Class:
o Represents a file or directory path in the file system.
o Provides methods for creating, deleting, renaming files and directories, and
checking file properties (like size, read/write permissions).
2. FileInputStream and FileOutputStream:
o Used for reading from and writing to files in binary format.
o Suitable for handling binary data like images, audio files, etc.
3. FileReader and FileWriter:
o Used for reading from and writing to files in character format.
o Ideal for text files and handles character encoding.
4. java.nio.file package:
o Introduces the Path and Files classes for more advanced file operations and better
handling of file paths.

Common Operations in File Handling:


• Creating Files: Initializing new files in the specified directory.
• Reading Files: Accessing file content for display or processing.
• Writing to Files: Storing data in files, either by overwriting existing content or appending to
it.
• Renaming Files: Changing the name of an existing file.

82
• Deleting Files: Removing files from the file system.
• Listing Directories: Retrieving and displaying the names of files within a directory.

1. Create a file named MyProfile.txt. Write your own profile into the file, MyProfile.txt.

Copy this file into another location and delete the file, MyProfile.txt.

Program :

import java.io.*;

import java.nio.file.*;

public class ProfileManager {

public static void main(String[] args) {

String fileName = "MyProfile.txt";

String copyLocation = "backup/MyProfile.txt"; // Adjust the path as needed

try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {

writer.write("Name: Your Name\n");

writer.write("Age: Your Age\n");

writer.write("Location: Your Location\n");

writer.write("Interests: Your Interests\n");

writer.write("Profession: Your Profession\n");

writer.write("About Me: I am a passionate individual who enjoys [a brief


description].\n");

} catch (IOException e) {

e.printStackTrace();

try {

83
Files.createDirectories(Paths.get("backup")); // Create the backup directory if it
doesn't exist

Files.copy(Paths.get(fileName), Paths.get(copyLocation),
StandardCopyOption.REPLACE_EXISTING);

System.out.println("File copied to: " + copyLocation);

} catch (IOException e) {

e.printStackTrace();

try {

Files.delete(Paths.get(fileName));

System.out.println(fileName + " has been deleted.");

} catch (IOException e) {

e.printStackTrace();

OUTPUT:

84
2. Perform the following operations on file using menu-driven application:
➢ Opening a existing file
➢ Creating a new file
➢ Renaming a file
➢ Deleting a file
➢ Creating a directory
➢ Finding the absolute path of a file
➢ Get the file names of a directory

Program :

OUTPUT :

package exercise9;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Scanner;

public class FileOperations {

public static void displayMenu() { System.out.println("Menu:"); System.out.println("1. Open


an existing file"); System.out.println("2. Create a new file"); System.out.println("3. Rename a
file"); System.out.println("4. Delete a file"); System.out.println("5. Create a directory");

System.out.println("6. Find the absolute path of a file"); System.out.println("7. Get the file
names of a directory"); System.out.println("8. Exit");

public static void openFile(String filename) {

try {

Scanner fileReader = new Scanner(new File(filename)); System.out.println("File content:");

while (fileReader.hasNextLine()) { System.out.println(fileReader.nextLine());

}
85
fileReader.close();

} catch (IOException e) { System.out.println("File not found.");

public static void createFile(String filename) {

try {

File file = new File(filename);

if (file.createNewFile()) {

System.out.println("File '" + filename + "' created successfully.");

} else {

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

} catch (IOException e) { System.out.println("Error creating file.");

public static void renameFile(String oldName, String newName) { File oldFile = new
File(oldName);

File newFile = new File(newName);

if (oldFile.renameTo(newFile)) {

System.out.println("File renamed from '" + oldName + "' to '" + newName + "'.");

} else {

System.out.println("Error renaming file.");

}
86
public static void deleteFile(String filename) { File file = new File(filename);

if (file.delete()) {

System.out.println("File '" + filename + "' deleted successfully.");

} else {

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

public static void createDirectory(String directoryName) { File directory = new


File(directoryName);

if (directory.mkdir()) {

System.out.println("Directory '" + directoryName + "' created successfully.");

} else {

System.out.println("Directory already exists or error creating directory.");

public static void findAbsolutePath(String filename) { File file = new File(filename);

try {

System.out.println("Absolute path of '" + filename + "': " + file.getAbsolutePath());

} catch (Exception e) {

System.out.println("Error finding absolute path.");

public static void listFilesInDirectory(String directoryName) { File directory = new


File(directoryName);

87
String[] files = directory.list();

if (files != null) {

System.out.println("Files in '" + directoryName + "': ");

for (String file : files) { System.out.println(file);

} else {

System.out.println("Directory not found or it's empty.");

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

while (true) {

displayMenu();

System.out.print("Choose an option (1-8): "); int choice = scanner.nextInt();


scanner.nextLine(); // Consume newline

switch (choice) {

case 1:

System.out.print("Enter the filename to open: "); String openFilename = scanner.nextLine();


openFile(openFilename);

break; case 2:

System.out.print("Enter the new filename: "); String createFilename = scanner.nextLine();


createFile(createFilename);

break; case 3:

88
System.out.print("Enter the current filename: "); String oldName = scanner.nextLine();
System.out.print("Enter the new filename: "); String newName = scanner.nextLine();
renameFile(oldName, newName);

break; case 4:

System.out.print("Enter the filename to delete: "); String deleteFilename =


scanner.nextLine(); deleteFile(deleteFilename);

break; case 5:

System.out.print("Enter the directory name to create: "); String directoryName =


scanner.nextLine(); createDirectory(directoryName);

break; case 6:

System.out.print("Enter the filename to find the absolute path: "); String absPathFilename =
scanner.nextLine(); findAbsolutePath(absPathFilename);

break; case 7:

System.out.print("Enter the directory name to list files: "); String listDirectoryName =


scanner.nextLine(); listFilesInDirectory(listDirectoryName);

break; case 8:

System.out.println("Exiting..."); scanner.close();

return; default:

System.out.println("Invalid option. Please try again.");

89
RESULT :

The program for File Handling has been completed and output is verified successfully.

90

You might also like