FileDemoDeleteRecord Example


import java.io.*;
import java.util.Scanner;

public class FileDeleteExample {

    public static void main(String[] args) {

        Scanner sin = new Scanner(System.in);
        System.out.println("Enter Student name whose record to be deleted");
        String sname = sin.next();
        File infile = new File("d:/mydatafile/stud.txt");
        File tempfile = new File("d:/mydatafile/temp.txt");
       
        String instr=null;
        try {
           
            FileReader fr = new FileReader(infile);
        BufferedReader br = new BufferedReader(fr);
       
        BufferedWriter bw = new BufferedWriter(new FileWriter(tempfile));
        while ( (instr=br.readLine() ) !=null )
        {
         
            if (instr.startsWith(sname))  continue;
           else
            {
                bw.write(instr); bw.newLine();
            }      
       
        }
        br.close(); fr.close();
        bw.close();
        if (!infile.delete())
                System.out.println("File can not be deleted");
        if (!tempfile.renameTo(infile))
                System.out.println("File cannot be renamed");      
           
       
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Comments

Popular posts from this blog

Custom Exception example for BankAccount

HashMap HashSet example

Annotation