Page 622 - ComputerScience_Class_11
P. 622

Program 28     Write a program to create and search a binary file with name and roll number.

                 1       import java.io.*;
                 2       import java.util.*;
                 3       class StudentBinaryFile
                 4       {
                 5           int rollno;
                 6           String name;
                 7           void createFile() throws IOException
                 8           {
                                  DataOutputStream dos = new DataOutputStream(new FileOutputStream("students.
                 9                dat"));
                10               Scanner sc = new Scanner(System.in);
                11               char choice = 'y';
                12               while (choice == 'y' || choice == 'Y')
                13               {
                14                   System.out.print("Enter roll number: ");
                15                   rollno = sc.nextInt();
                16                   sc.nextLine();
                17                   System.out.print("Enter student name: ");
                18                   name = sc.nextLine();
                19                   dos.writeInt(rollno);
                20                   dos.writeUTF(name);
                21                   System.out.print("Do you want to add another student? (y/n): ");
                22                   choice = sc.next().charAt(0);
                23               }
                24               dos.close();
                25               System.out.println("Student records have been written to the file.");
                26           }
                27           void searchStudent(int rollnoToSearch) throws IOException
                28           {
                                  DataInputStream dis = new DataInputStream(new FileInputStream("students.
                29                dat"));
                30               boolean found = false;
                31               while (dis.available() > 0)
                32               {
                33                   int rollno = dis.readInt();
                34                   String name = dis.readUTF();
                35                   if (rollno == rollnoToSearch)
                36                   {

                                          System.out.println("Student found: Roll No: " + rollno +  ",
                37                          Name: " + name);
                38                       found = true;
                39                       break;
                40                   }




                  620  Touchpad Computer Science (Ver. 3.0)-XI
   617   618   619   620   621   622   623   624   625   626   627