I have another problem this time if anyone can help with random files i am writting and displaying records from the while but i want to display all records in the file that has data say i have 100 records but only 15 contain user data i want to display only those 15 here is what i have so far. I am getting an exception on line 198.

cont.. james when reading from the scanner brings up errors as random file data is basically on the same line
does java RandomAccesFile class have a method like hasnext with the scanner to scan the random file ?

public static void displayFile()
    {
        int id = 0;
        int age;
        String name;
        String school;
        try
        {
            Scanner data = new Scanner(new File("Test.txt"));
            RandomAccessFile get = new RandomAccessFile("Test.txt","rw");
            while(data.hasNext()) 
            {
                //store variables from random with random instance
                 id = get.readInt();
                 age = get.readInt();
                 name= get.readUTF();
                 school = get.readUTF();

                if(id!= 0)
                 {
                    // display data if id number is not 0
                     System.out.println("\nId # :" +id);
                     System.out.println("age :" +age);
                     System.out.println("Name :" +name);
                     System.out.println("School :" +school);
                 }
                 else if(id == 100)
                 { 
                     System.out.println("Last record");
                 }  
            }// while
        }
        catch(IOException A)
        {
            System.err.println("could not display file");
            A.printStackTrace();
        }
    }// end of method

you're getting an error on line 198 and you think we know what that line does (wrong) by only showing us 38 lines?

You can keep reading data from the RandomAccessFile until it reaches end-of-file, at which point it throws an EOFException which you can catch to end the processing tidily. Or you can getFilePointer() before trying to read each record and test that it is less than the file's length(). Either way, there's no need or use for the Scanner.
ps: Why use a RandomAccessFile when you are just reading ot sequentially?

My bad line 198 is actually line 16 in this code...i have a good understanding of sequential files(completed my project) i just wanted to understand how to use RandomAccessFile

This article has been dead for over six months. Start a new discussion instead.