Você está na página 1de 3

RANDOM ACCESS FILES AND AWT

SORTING STRINGS FROM A RANDOM ACCESS FILE USING A LOOK UP INDEX ARRAY 1. 2. 3. 4. Get a count of how many valid records exist in the data file. Make a String[] array of that size/count. Make an Integer[] array of that size/count. Open the file in 'READ' mode and load every valid name into the String[] array and it's record number into the Integer[] array. So, if your data file contained the following valid names and record numbers Record # 0 1 2 3 4 5 Name Marcus Chia Maria Dahl John Smith Suraj Raveendran Robert Jones Jim Cook

Then your String[] and Integer[] Arrays will look like below: Integer[] Array 0 0 1 1 2 2 3 3 4 4 5 5 String[] Array 0 Marcus Chia 1 Maria Dahl 2 John Smith 3 Suraj Raveendran 4 Robert Jones 5 Jim Cook

5. The rest is pretty straight forward use a nested FOR loop and sort the String[] array either in Ascending (A-Z) or Descending (Z-A) order. To do this, we use the following code:
String temp; //to hold String temporarily during sort int tempR; //to hold Record # temporarily during sort for(int i=0;i<stringArray.length();i++) { for(int j=0;j<stringArray.length();j++) { if(names[i].compareTo(names[j]) < 0) //value is <0 if first value is GREATER than second value. { temp = names[i];//use 'temp' variable to hold String value names[i]=names[j];//swap the first value names[j]=temp;//swap the second value tempR = recordPos[i];//do the same for the 'Record #' too since the array. recordPos[i]=recordPos[j]; recordPos[j]=tempR;

} } }

6. Now what this does, is sorts the String[] array and the Integer[] array according to the alphabetical order. In this example the names will be sorted in the ASCENDING order (A-Z) so from the above example, the data in the arrays will now look like this: Integer[] Array 0 5 1 2 2 0 3 1 4 4 5 3 String[] Array 0 Jim Cook 1 John Smith 2 Marcus Chia 3 Maria Dahl 4 Robert Jones 5 Suraj Raveendran

7. Final step: Now loop through the Integer[] array and use the SEEK() method to go directly to that record from the file and print that record's details. The idea of sorting the name was to ensure the record numbers also got sorted correctly in that process. try
{ RandomAccessFile rf = new RandomAccessFile(FriendsDB, r); rf.seek(0); for(int i=0;i<recordArray.length();i++) { rf.seek(recordArray[i]*recordSize);

//go to record # in the array position

rf.readInt(); //skip record # if needed System.out.println(rf.readUTF( )); //print firstname / full name //You can also choose to display this information in a text area in your AWT Window which //can then be //printed to an Excel sheet for a hard copy. }//end of for rf.close(); //close the file }catch(IOException e) {statusLBL.setText(Error: + e };

Você também pode gostar