Search Product Code in a Binary File

A binary file named “ABC.DAT” contains the product code, unit price and quantity for number of items.

Write a method to accept a product code ‘p’ and check the availability of the product and display with an appropriate message.

The method declaration is as follows:

void findpro(int p)

public static void findpro(int p)throws IOException{
    boolean found = false;
    boolean eof = false;
    FileInputStream fis = new FileInputStream ("ABC.dat");
    DataInputStream dis = new DataInputStream (fis);
    while (!eof){
        try{
            int pc = dis.readInt();
            double price = dis.readDouble();
            int q = dis.readInt();
            if (p==pc){
                found = true;
                break;
            }
        }catch(EOFException e){
            System.out.println("Reached end of file!");
            eof=true;
        }
    }
    if(found)
        System.out.println(p+ " is available");
    else
        System.out.println(p+ " not found");
    dis.close();
    fis.close();
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.