Tuesday , 5 December 2017
Home » Class 12 » Sample Programs on Operations on Text Files for ISC Computer Science

Sample Programs on Operations on Text Files for ISC Computer Science

Below are the sample codes of the operations performed on a text file. These operations include:

  1. Creating and Writing to a Text File
  2. Reading and Displaying from a Text File
  3. Copying the records of a Text File into another Text File
  4. Deleting a record from a File
  5. Inserting a record into a File
  6. Deleting a file completely
  7. Renaming an old file to a new file name
  8. Editing/Replacing a record in a File
  9. Sorting the records stored in the file in alphabetical order
  10. Searching for a record in a file
  11. Merging 2 files into a single file

Codes of all the above operations have been written in a single class, each one written in a separate method.

Note: All the file names you enter for the above operations when you are asked must be valid and it must be present in the same directory (except for the operation of creating a file) where your programs are saved.

When you are asked for a filename, then give the complete filename along with it’s extension like “Sample.txt”

If you want to print a copy of the below code, then the PDF file of the codes can be downloaded from here: Programming codes for Operations on Files [ISC Computer Science]

Programming Code: 

/** @author : www.javaforschool.com
 *  @Topic : Operations on Text Files 
 *  @Program Type : BlueJ Program – Java
 */

import java.io.*;
class OperationOnFile
{
static BufferedReader b=new BufferedReader (new InputStreamReader(System.in));

/* Creating and Writing to a File */

void create(String fileName, int n)throws IOException
    {
     FileWriter fw=new FileWriter(fileName,false);
     BufferedWriter bw=new BufferedWriter(fw);
     PrintWriter pw=new PrintWriter(bw);
     String name;
     for(int i=0; i<n; i++)
        {
         System.out.print("Enter name "+(i+1)+" : ");
         name=b.readLine();
         pw.println(name);
        }
     System.out.println("File created successfully !");
     pw.close(); 
     bw.close();  
     fw.close();
    }

/* Reading and Displaying from a File */

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();
    }      

/* Copying the records of a Text File into another Text File */

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();
    }  

/* Note: To delete or Rename a file, you need to create a File Class object pointing to the file 
you want to delete or rename. */

/* Deleting a file completely */

void delFile(String fileName)
    {
     File f1=new File(fileName);	//creation of object for 1st file
     f1.delete();           		//This line deletes the file
     System.out.println("File deleted successfully !");
    }

/* Renaming an old file to a new file name */

void renFile(String oldfile, String newfile)
    {
     File f1=new File(oldfile); 	//creation of object for 1st file
     File f2=new File(newfile);	//creation of object for 2nd file
     boolean r=f1.renameTo(f2); 
/* The above line renames the old file with the new file name & deletes the old file */
     if(r==true)
       System.out.println("File Renamed successfully !");
     else
       System.out.println("Unable to Rename. Check whether the file already exists."); 
     }

/* Inserting a record into a File */

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);//put this line before pw.println(name) to insert before
      }
      br.close(); fr.close();  pw.close();  bw.close();  fw.close();
      copy("TEMP.TXT",fileName);
      System.out.println("Record inserted successfully !");
    }

/* NOTE: In the above function, use "fw" with "true" to append to the current file i.e. to insert
at end of the file */

/* Deleting a record from a File */

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 !");
    }
/* Editing/Replacing a record in a File */

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 !");
    } 

/* Sorting the names stored in the file in alphabetical order */ 

void sort(String fileName)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;
      int p=0;
      String tempName[]=new String[100];
      while((name=br.readLine())!=null)
                {
                    tempName[p++]=name;
                }
      String temp="";
      for(int i=0;i<p-1;i++)
      {
          for(int j=i+1;j<p;j++)
          {
              if(tempName[i].compareTo(tempName[j])>0)
              {
                  temp=tempName[i];
                  tempName[i]=tempName[j];
                  tempName[j]=temp;
              }
          }
      }
      System.out.println("nThe file currently contains the following:");
      display(fileName);
      System.out.println("The Names after sorting Alphabetically are: ");
      for(int i=0; i<p; i++)
        {
         pw.println(tempName[i]);
        }
      br.close();  fr.close();  pw.close();  bw.close();  fw.close();
      copy("TEMP.TXT",fileName);
      display(fileName);
    } 

/* Searching for a record in a file */

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();
    }

/* Merging 2 files into a single file */

/* Note: For Merging files, the files being merged must exist and contain some values in them. 
In this case the 1st file must contain "Names" of few person and the 2nd file must contain 
the "Pan Card number" of those persons. Both these files will be merged into a
single new file. */

void merge(String file1, String file2, String file3)throws IOException
    {
      String pan,name;
      int p=0,q=0;
      String tempPan[]=new String[100];
      String tempName[]=new String[100];
      FileReader fr1 = new FileReader(file1);
      BufferedReader br1 = new BufferedReader(fr1);
      FileReader fr2 = new FileReader(file2);
      BufferedReader br2 = new BufferedReader(fr2);
      FileWriter fw=new FileWriter(file3,false);
      BufferedWriter bw=new BufferedWriter(fw);
      PrintWriter pw=new PrintWriter(bw);
      pw.println("NAMEttPAN");
      while((name=br1.readLine())!=null)
        {
         tempName[p++]=name;
        }
      while((pan=br2.readLine())!=null)
        {
         tempPan[q++]=pan;
        }
      for(int i=0; i<p; i++)
        {
         String str=tempName[i]+"tt"+tempPan[i];
         pw.println(str);
        }
      br1.close();
      fr1.close();
      br2.close();
      fr2.close();
      pw.close();
      bw.close();
      fw.close();
      System.out.println("Files Merged successfully !");
    }
/* Note: All the file names you enter for the below operations except creating a file, 
must be valid and it must be present in the same directory where your programs are saved. 
When you are asked for a filename, then give the complete filename along with it's extension
like "Sample.txt" */

public static void main(String args[])throws IOException
  {
     OperationOnFile ob=new OperationOnFile(); //creating an object to call the methods

     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=Integer.parseInt(b.readLine());

     if(ch==1)
      {
        System.out.print("nEnter a File Name to Create: ");
        String file= b.readLine();
        System.out.print("Enter the number of names to insert: ");
        int n=Integer.parseInt(b.readLine());
        ob.create(file, n);
      }
    else if(ch==2)
      {
        System.out.print("nEnter a File Name to Read from: ");
        String file= b.readLine();
        ob.display(file);
      }
    else if(ch==3)
      {
        System.out.print("nEnter a File Name to Copy from: ");
        String file1= b.readLine();
        System.out.print("Enter the File Name to Copy to: ");
        String file2= b.readLine();
        ob.copy(file1,file2);
      }
    else if(ch==4)
      {
        System.out.print("nEnter a File Name to Delete Record from: ");
        String file= b.readLine();
        System.out.println("nThe file currently contains the following:");
        ob.display(file);
        System.out.print("Enter the name to delete: ");
        String name= b.readLine();
        ob.delete(file,name);
      }
    else if(ch==5)
      {
        System.out.print("nEnter a File Name to Insert into: ");
        String file= b.readLine();
        System.out.println("nThe file currently contains the following:");
        ob.display(file);
        System.out.print("Enter the name to Insert: ");
        String name= b.readLine();
        System.out.print("Enter the name after which it is to be inserted: ");
        String nameafter= b.readLine();
        ob.insert(file,name,nameafter);
       }
    else if(ch==6)
      {
        System.out.print("nEnter a File Name to Edit: ");
        String file= b.readLine();
        System.out.println("nThe file currently contains the following:");
        ob.display(file);
        System.out.print("Enter the Old name to be replaced: ");
        String oldname= b.readLine();
        System.out.print("Enter the New name: ");
        String newname= b.readLine();
        ob.edit(file,oldname,newname);
      }
    else if(ch==7)
      {
        System.out.print("nEnter the File Name to Delete: ");
        String file= b.readLine();
        ob.delFile(file);
      }
    else if(ch==8)
      {
        System.out.print("nEnter the file name to Rename: ");
        String file1= b.readLine();
        System.out.print("Enter the New file name: ");
        String file2= b.readLine();
        ob.renFile(file1,file2);
      }

    else if(ch==9)
      {
        System.out.print("nEnter the File Name to Sort: ");
        String file= b.readLine();
        ob.sort(file);
      }

    else if(ch==10)
      {
        System.out.print("nEnter the name of the file to search into: ");
        String file= b.readLine();
        System.out.print("Enter the name to search: ");
        String s= b.readLine();
        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= b.readLine();
        System.out.print("Enter the name of First file: ");
        String file2= b.readLine();
        System.out.print("Enter name of New file where the files will be merged: ");
        String file3= b.readLine();
        ob.merge(file1,file2,file3);
      }
    else
     {
        System.exit(0);
     }
  }
}

Check Also

[Question 2] ISC 2017 Computer Practical Paper Solved – Quiz Result

Solution of Program 2 of ISC 2017 Computer Science Paper 2 (Practical) Exam. Java program to input the answers of each participant row-wise and calculate their marks

Leave a Reply

Your email address will not be published. Required fields are marked *