Operations on Text Files Program in Java and Python
Sample Java and Python programs for common text file operations such as create, display, copy, insert, delete, edit, sort, search, merge, rename and delete.
Question:
Write sample programs to perform common operations on text files for ISC Computer Science. The operations include:
- Creating and writing to a text file.
- Reading and displaying records from a text file.
- Copying records from one text file into another text file.
- Deleting a record from a file.
- Inserting a record into a file.
- Deleting a file completely.
- Renaming an old file to a new file name.
- Editing or replacing a record in a file.
- Sorting the records stored in the file in alphabetical order.
- Searching for a record in a file.
- Merging two files into a single file.
Write the codes for the above operations in a single class, with each operation written in a separate method. All file names entered by the user must be valid. Except while creating a new file, the file must already be present in the same folder where the program is saved. When a file name is asked, enter the complete file name with its extension, such as Sample.txt.
Example
Algorithm:
Step 1: Start.
Step 2: Define a class named OperationOnFile and create a Scanner object for console input.
Step 3: In create(), open the given file with FileWriter, accept n names and write each name with PrintWriter.
Step 4: In display(), open the file with FileReader and print each line until readLine() returns null.
Step 5: In copy(), read every line from the first file and write it to the second file.
Step 6: In delFile(), create a File object and call delete().
Step 7: In renFile(), create two File objects and call renameTo().
Step 8: In insert(), copy all records to a temporary file and write the new record after the matching record.
Step 9: In delete(), copy all records except the record to be deleted into a temporary file, then copy the temporary file back.
Step 10: In edit(), replace the matching record with a new value while copying records to a temporary file.
Step 11: In sort(), store all records in an array, sort them alphabetically and write them back to the file.
Step 12: In search(), read each record and compare it with the search value using case-insensitive comparison.
Step 13: In merge(), read names from one file and PAN numbers from another file, then write combined records into a new file.
Step 14: In main(), display a menu, accept the user's choice and call the corresponding method.
Step 15: Stop.
Explanation:
This program is a collection of common text file operations. Each operation is placed in a separate method so that the logic remains organized. Text files store data as lines of characters. In this program, each line is treated as one record, usually a name. Reading a file means taking one line at a time from the file, and writing a file means sending one record at a time to the file.
The program uses Scanner for keyboard input, because the user must enter choices, file names and records. For file handling, it uses Java file classes. FileReader and BufferedReader are used to read existing files line by line. FileWriter, BufferedWriter and PrintWriter are used to write records into files. The writing mode is usually false, which means the file is overwritten with fresh contents. This is useful when copying, sorting, editing or deleting records.
Some operations cannot be done directly inside the same file while reading it. For example, to delete or edit a record, the program reads the original file and writes the required records into a temporary file. After that, the temporary file is copied back into the original file. This is a standard school-level method for updating text files safely. Inserting a record also uses this idea: the program copies each line and writes the new record after the selected line.
Sorting first stores all records in an array, then compares strings using compareTo(). If one name comes after another alphabetically, the two are swapped. Searching reads each record and compares it with the required name using equalsIgnoreCase(), so the search is not affected by uppercase or lowercase differences. Merging reads two separate files into arrays and writes related values into a third file using a tab between them.
Java Program:
/**
* The class OperationOnFile demonstrates common operations on text files.
* @author : www.guideforschool.com
* @Topic : Operations on Text Files
* @Program Type : BlueJ Program - Java
*/
import java.io.*;
import java.util.Scanner;
class OperationOnFile
{
static Scanner sc = new Scanner(System.in);
void create(String fileName, int n) throws IOException
{
FileWriter fw = new FileWriter(fileName, false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
for(int i = 0; i < n; i++)
{
System.out.print("Enter name " + (i + 1) + " : ");
String name = sc.nextLine();
pw.println(name);
}
System.out.println("File created successfully !");
pw.close();
bw.close();
fw.close();
}
void display(String fileName) throws IOException
{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String name;
while((name = br.readLine()) != null)
{
System.out.println("Entry : " + name);
}
System.out.println("--end--");
br.close();
fr.close();
}
void copy(String file1, String file2) throws IOException
{
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(file2, false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
String name;
while((name = br.readLine()) != null)
{
pw.println(name);
}
br.close();
fr.close();
pw.close();
bw.close();
fw.close();
}
void delFile(String fileName)
{
File f1 = new File(fileName);
f1.delete();
System.out.println("File deleted successfully !");
}
void renFile(String oldfile, String newfile)
{
File f1 = new File(oldfile);
File f2 = new File(newfile);
boolean r = f1.renameTo(f2);
if(r)
System.out.println("File Renamed successfully !");
else
System.out.println("Unable to Rename. Check whether the file already exists.");
}
void insert(String fileName, String name2insert, String after) throws IOException
{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("TEMP.TXT", false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
String name;
while((name = br.readLine()) != null)
{
pw.println(name);
if(name.equalsIgnoreCase(after))
pw.println(name2insert);
}
br.close();
fr.close();
pw.close();
bw.close();
fw.close();
copy("TEMP.TXT", fileName);
System.out.println("Record inserted successfully !");
}
void delete(String fileName, String name2delete) throws IOException
{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("TEMP.DAT", false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
String name;
while((name = br.readLine()) != null)
{
if(!name.equalsIgnoreCase(name2delete))
pw.println(name);
}
br.close();
fr.close();
pw.close();
bw.close();
fw.close();
copy("TEMP.DAT", fileName);
System.out.println("Record deleted successfully !");
}
void edit(String fileName, String oldName, String newName) throws IOException
{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("TEMP.TXT", false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
String name;
while((name = br.readLine()) != null)
{
if(name.equalsIgnoreCase(oldName))
name = newName;
pw.println(name);
}
br.close();
fr.close();
pw.close();
bw.close();
fw.close();
copy("TEMP.TXT", fileName);
System.out.println("Record Edited successfully !");
}
void sort(String fileName) throws IOException
{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String tempName[] = new String[100];
String name;
int p = 0;
while((name = br.readLine()) != null)
{
tempName[p++] = name;
}
for(int i = 0; i < p - 1; i++)
{
for(int j = i + 1; j < p; j++)
{
if(tempName[i].compareTo(tempName[j]) > 0)
{
String temp = tempName[i];
tempName[i] = tempName[j];
tempName[j] = temp;
}
}
}
br.close();
fr.close();
FileWriter fw = new FileWriter("TEMP.TXT", false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
for(int i = 0; i < p; i++)
{
pw.println(tempName[i]);
}
pw.close();
bw.close();
fw.close();
copy("TEMP.TXT", fileName);
System.out.println("The Names after sorting Alphabetically are:");
display(fileName);
}
void search(String fileName, String nameSearch) throws IOException
{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String name;
int flag = 0;
while((name = br.readLine()) != null)
{
if(name.equalsIgnoreCase(nameSearch))
{
flag = 1;
break;
}
}
if(flag == 1)
System.out.println("Search Successful ! Record is present in the File");
else
System.out.println("Sorry ! The record is not present");
br.close();
fr.close();
}
void merge(String file1, String file2, String file3) throws IOException
{
String tempName[] = new String[100];
String tempPan[] = new String[100];
int p = 0;
int q = 0;
String name;
String pan;
FileReader fr1 = new FileReader(file1);
BufferedReader br1 = new BufferedReader(fr1);
FileReader fr2 = new FileReader(file2);
BufferedReader br2 = new BufferedReader(fr2);
while((name = br1.readLine()) != null)
tempName[p++] = name;
while((pan = br2.readLine()) != null)
tempPan[q++] = pan;
FileWriter fw = new FileWriter(file3, false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.println("NAME\tPAN");
for(int i = 0; i < p && i < q; i++)
{
pw.println(tempName[i] + "\t" + tempPan[i]);
}
br1.close();
fr1.close();
br2.close();
fr2.close();
pw.close();
bw.close();
fw.close();
System.out.println("Files Merged successfully !");
}
public static void main(String args[]) throws IOException
{
OperationOnFile ob = new OperationOnFile();
System.out.println("Enter 1 for Creating a file.");
System.out.println("Enter 2 for Reading from a file.");
System.out.println("Enter 3 for Copying a file.");
System.out.println("Enter 4 for Deleting a record from a file.");
System.out.println("Enter 5 for Inserting a record into a file.");
System.out.println("Enter 6 for Editing/Replacing a record from a file.");
System.out.println("Enter 7 for Deleting a file.");
System.out.println("Enter 8 for Renaming a file.");
System.out.println("Enter 9 for Sorting a file.");
System.out.println("Enter 10 for Searching in a file.");
System.out.println("Enter 11 for Merging 2 files.");
System.out.println("Enter any other number to Exit.");
System.out.print("\nEnter your Choice: ");
int ch = sc.nextInt();
sc.nextLine();
if(ch == 1)
{
System.out.print("\nEnter a File Name to Create: ");
String file = sc.nextLine();
System.out.print("Enter the number of names to insert: ");
int n = sc.nextInt();
sc.nextLine();
ob.create(file, n);
}
else if(ch == 2)
{
System.out.print("\nEnter a File Name to Read from: ");
String file = sc.nextLine();
ob.display(file);
}
else if(ch == 3)
{
System.out.print("\nEnter a File Name to Copy from: ");
String file1 = sc.nextLine();
System.out.print("Enter the File Name to Copy to: ");
String file2 = sc.nextLine();
ob.copy(file1, file2);
}
else if(ch == 4)
{
System.out.print("\nEnter a File Name to Delete Record from: ");
String file = sc.nextLine();
System.out.println("\nThe file currently contains the following:");
ob.display(file);
System.out.print("Enter the name to delete: ");
String name = sc.nextLine();
ob.delete(file, name);
}
else if(ch == 5)
{
System.out.print("\nEnter a File Name to Insert into: ");
String file = sc.nextLine();
System.out.println("\nThe file currently contains the following:");
ob.display(file);
System.out.print("Enter the name to Insert: ");
String name = sc.nextLine();
System.out.print("Enter the name after which it is to be inserted: ");
String nameafter = sc.nextLine();
ob.insert(file, name, nameafter);
}
else if(ch == 6)
{
System.out.print("\nEnter a File Name to Edit: ");
String file = sc.nextLine();
System.out.println("\nThe file currently contains the following:");
ob.display(file);
System.out.print("Enter the Old name to be replaced: ");
String oldname = sc.nextLine();
System.out.print("Enter the New name: ");
String newname = sc.nextLine();
ob.edit(file, oldname, newname);
}
else if(ch == 7)
{
System.out.print("\nEnter the File Name to Delete: ");
String file = sc.nextLine();
ob.delFile(file);
}
else if(ch == 8)
{
System.out.print("\nEnter the file name to Rename: ");
String file1 = sc.nextLine();
System.out.print("Enter the New file name: ");
String file2 = sc.nextLine();
ob.renFile(file1, file2);
}
else if(ch == 9)
{
System.out.print("\nEnter the File Name to Sort: ");
String file = sc.nextLine();
ob.sort(file);
}
else if(ch == 10)
{
System.out.print("\nEnter the name of the file to search into: ");
String file = sc.nextLine();
System.out.print("Enter the name to search: ");
String s = sc.nextLine();
ob.search(file, s);
System.out.println("\nThe file currently contains the following:");
ob.display(file);
}
else if(ch == 11)
{
System.out.print("\nEnter the name of First file: ");
String file1 = sc.nextLine();
System.out.print("Enter the name of Second file: ");
String file2 = sc.nextLine();
System.out.print("Enter name of New file where the files will be merged: ");
String file3 = sc.nextLine();
ob.merge(file1, file2, file3);
}
else
{
System.exit(0);
}
}
}Equivalent Python Program:
# Sample program for common text file operations.
import os
def create(file_name, n):
with open(file_name, "w") as f:
for i in range(n):
name = input("Enter name " + str(i + 1) + " : ")
f.write(name + "\n")
print("File created successfully !")
def display(file_name):
with open(file_name, "r") as f:
for line in f:
print("Entry :", line.strip())
print("--end--")
def copy(file1, file2):
with open(file1, "r") as source, open(file2, "w") as target:
for line in source:
target.write(line)
def insert(file_name, name_to_insert, after):
with open(file_name, "r") as f:
lines = f.readlines()
with open(file_name, "w") as f:
for line in lines:
f.write(line)
if line.strip().lower() == after.lower():
f.write(name_to_insert + "\n")
print("Record inserted successfully !")
def delete_record(file_name, name_to_delete):
with open(file_name, "r") as f:
lines = f.readlines()
with open(file_name, "w") as f:
for line in lines:
if line.strip().lower() != name_to_delete.lower():
f.write(line)
print("Record deleted successfully !")
def edit(file_name, old_name, new_name):
with open(file_name, "r") as f:
lines = f.readlines()
with open(file_name, "w") as f:
for line in lines:
if line.strip().lower() == old_name.lower():
f.write(new_name + "\n")
else:
f.write(line)
print("Record Edited successfully !")
def sort_file(file_name):
with open(file_name, "r") as f:
names = [line.strip() for line in f if line.strip()]
names.sort()
with open(file_name, "w") as f:
for name in names:
f.write(name + "\n")
print("The Names after sorting Alphabetically are:")
display(file_name)
def search(file_name, name_search):
found = False
with open(file_name, "r") as f:
for line in f:
if line.strip().lower() == name_search.lower():
found = True
break
if found:
print("Search Successful ! Record is present in the File")
else:
print("Sorry ! The record is not present")
def merge(file1, file2, file3):
with open(file1, "r") as f1:
names = [line.strip() for line in f1]
with open(file2, "r") as f2:
pans = [line.strip() for line in f2]
with open(file3, "w") as f3:
f3.write("NAME\tPAN\n")
for i in range(min(len(names), len(pans))):
f3.write(names[i] + "\t" + pans[i] + "\n")
print("Files Merged successfully !")
print("Enter 1 for Creating a file.")
print("Enter 2 for Reading from a file.")
print("Enter 3 for Copying a file.")
print("Enter 4 for Deleting a record from a file.")
print("Enter 5 for Inserting a record into a file.")
print("Enter 6 for Editing/Replacing a record from a file.")
print("Enter 7 for Deleting a file.")
print("Enter 8 for Renaming a file.")
print("Enter 9 for Sorting a file.")
print("Enter 10 for Searching in a file.")
print("Enter 11 for Merging 2 files.")
print("Enter any other number to Exit.")
choice = int(input("\nEnter your Choice: "))
if choice == 1:
file = input("\nEnter a File Name to Create: ")
n = int(input("Enter the number of names to insert: "))
create(file, n)
elif choice == 2:
file = input("\nEnter a File Name to Read from: ")
display(file)
elif choice == 3:
file1 = input("\nEnter a File Name to Copy from: ")
file2 = input("Enter the File Name to Copy to: ")
copy(file1, file2)
elif choice == 4:
file = input("\nEnter a File Name to Delete Record from: ")
display(file)
name = input("Enter the name to delete: ")
delete_record(file, name)
elif choice == 5:
file = input("\nEnter a File Name to Insert into: ")
display(file)
name = input("Enter the name to Insert: ")
after = input("Enter the name after which it is to be inserted: ")
insert(file, name, after)
elif choice == 6:
file = input("\nEnter a File Name to Edit: ")
display(file)
old_name = input("Enter the Old name to be replaced: ")
new_name = input("Enter the New name: ")
edit(file, old_name, new_name)
elif choice == 7:
file = input("\nEnter the File Name to Delete: ")
os.remove(file)
print("File deleted successfully !")
elif choice == 8:
old_file = input("\nEnter the file name to Rename: ")
new_file = input("Enter the New file name: ")
os.rename(old_file, new_file)
print("File Renamed successfully !")
elif choice == 9:
file = input("\nEnter the File Name to Sort: ")
sort_file(file)
elif choice == 10:
file = input("\nEnter the name of the file to search into: ")
name = input("Enter the name to search: ")
search(file, name)
display(file)
elif choice == 11:
file1 = input("\nEnter the name of First file: ")
file2 = input("Enter the name of Second file: ")
file3 = input("Enter name of New file where the files will be merged: ")
merge(file1, file2, file3)Output:
Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.