Error sorting values from a binary file

2

I have the following code:

try{
    raf = new RandomAccessFile("Partides.dat", "rw");

    for (long i=0; i< "partides.dat".length(); i= i+48){

        for (long j=i +48; j<"partides.dat".length(); j=j+48){

            // Es llegueixen els valors de la posició punts
            raf.seek(i);
            double valorI= raf.readDouble();

            raf.seek(j);
            double valorJ = raf.readDouble();

            //Es comparen
            if (valorI > valorJ )
                //se intercanvian
                raf.seek(i);
            raf.writeDouble(valorJ);
            raf.seek(j);
            raf.writeDouble(valorI);
        }
    }
    raf.close();

I can not get my records ordered ... and I do not know what I'm doing wrong: S In this case I'm trying to order two values ..

Basically with the code I try to get it to order some data that are positioned in the 48 "ie the points" from highest to lowest. But if I understand my code well I am trying to order only 2 values .. I do not know if there is a way to sort them all in another way ..: S

I put the complete code to review:

/**
 * OPCIO 2  ACTIVITAT 3
 */
package activitat2;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
/**
 *
 * @author Montse
 */
public class Opcio2 {
    /**
     * En aquesta clase farem les demandes de l'activitat 2
     * @throws FileNotFoundException 
     */
    static void ActualitzarInstituts() throws FileNotFoundException, IOException {
        RandomAccessFile raf;
        raf = new RandomAccessFile("Partides.dat", "rw");
        System.out.println("--------------------------------");
        System.out.println("HAS ESCOLLIT OPCIÓ 2");
        System.out.println("--------------------------------");
        System.out.println("Escoge una opción:::::::");
        System.out.println("1-Actualizar Puntos y listar resultados");
        System.out.println("2-Instituto Ganador ");
        System.out.println("3-Percentatge dels millors instituts");
        System.out.println("4- Volver al menú principal");
        System.out.println("5- Salir");
        System.out.println("Escoje una opción");
        Scanner lector = new Scanner(System.in);
        int punts=0;
        int enterLlegit =0;
        boolean llegit = false;
        while(!llegit){
            llegit = lector.hasNextInt();
            if (llegit){
                enterLlegit = lector.nextInt();
                switch (enterLlegit) {
        case 1:
            System.out.println("--------------------------------------");
            System.out.println("HAS ESCOGIDO ACTUALIZAR PUNTOS");
            System.out.println("--------------------------------------");  
           for (int registro = 1;; registro++) {            
    int pos = 48 * (registro - 1);
    try {       
        pos += 4 + 20 + 20;
        // Lectura
        raf.seek(pos);
        System.out.printf("Instituto número: #%02d%n", registro);
        raf.seek(pos);
        System.out.printf("Puntos actuales: %d%n", raf.readInt());
        // Escritura
        raf.seek(pos);
        System.out.println("Introducir puntos: ");
         punts = lector.nextInt();
         System.out.println("-------------------------------------");
        raf.writeInt(punts);
        raf.seek(pos);  
          } catch (EOFException e) {
        // Fin de archivo
        raf.close();
         System.out.println("Datos actualizados:::");
         System.out.println("Tornem al menú principal");
         Opcio1.IntroduirInstituts();
break;
    } }break;

        case 2:
            System.out.println("-------------------------------------");
            System.out.println("HAS ESCOGIDO ORDENAR POR PUNTOS:");
             System.out.println("Instituto Ganador ");
             System.out.println("-------------------------------------");
             try{
                  raf = new RandomAccessFile("Partides.dat", "rw");
                 for (long i=0; i< "partides.dat".length(); i= i+48){
                     for (long j=i +48; j<"partides.dat".length(); j=j+48){

                         // Es llegueixen els valors de la posició punts
                         raf.seek(i);
                         double valorI= raf.readDouble();
                         raf.seek(j);
                         double valorJ = raf.readDouble();
                         //Es comparen
                         if (valorI > valorJ )                         
                             //se intercanvian
                             raf.seek(i);
                             raf.writeDouble(valorJ);
                             raf.seek(j);
                             raf.writeDouble(valorI);           
                         }
                     }raf.close();
                             //    ANEM A LLISTAR RESULTATS:
             System.out.println("Ves a la opción Listar para observar los cambios");
             Opcio1.IntroduirInstituts();

                 } catch (Exception e){
                     System.out.println("Error ordenado fichero");
                     }          
            break;

        case 3:
        System.out.println("Percentatge dels millors instituts");
        //PENDIENTE DE HACER //
            break;

             case 4:
            System.out.println("TORNAR AL MENÚ PRINCIPAL::::");
            MenuPrincipal.EscollirOpcio(); 
            break;

       case 5:
           System.out.println("HAS ESCOLLIT SORTIR");
System.out.println("Hasta la próxima!");
        break;      
        default:
System.out.println("No has escrito una opción válida");
System.out.println("Fin del programa");
        break;}
            }else{
                System.out.println("No has escrito un entero, vuelve a intentarlo");
                lector.next();
            }    
        }
        lector.nextLine();

    }
    
asked by Montse Mkd 07.01.2016 в 23:13
source

2 answers

3

You could sort the records using the java.lang.Comparable interface and the class java.util.Collections .

First you create a class that implements the mentioned interface. For example:

class Registro implements Comparable<Registro> {

    int id;
    String instituto;
    String equipo;
    int puntos;

    @Override
    public int compareTo(Registro o) {
        return o.puntos - puntos;
    }
}

The implementation of the compareTo method is used in the ordering process.

To store all records, you can use a list, that is, an instance of java.util.List :

List<Registro> list = new ArrayList<>();

In a cycle for , you create a Registro , read the corresponding data and add them to the list, until the end of the file:

for (int pos = 0;;) {
    try {
        Registro registro = new Registro();
        raf.seek(pos);
        registro.id = raf.readInt();
        pos += 4;

        raf.seek(pos);
        registro.instituto = raf.readUTF();
        pos += 20;

        raf.seek(pos);
        registro.equipo = raf.readUTF();
        pos += 20;

        raf.seek(pos);
        registro.puntos = raf.readInt();
        pos += 4;
        list.add(registro);
    } catch (EOFException e) {
        // Fin de archivo
        break;
    }
}

You sort the list using the sort method of the class java.util.Collections :

Collections.sort(list);

Once ordered, you write the records with another cycle for in the file:

for (int i = 0, pos = 0; i < list.size(); i++) {
    Registro registro = list.get(i);
    raf.seek(pos);
    raf.writeInt(registro.id);
    pos += 4;

    raf.seek(pos);
    raf.writeUTF(registro.instituto);
    pos += 20;

    raf.seek(pos);
    raf.writeUTF(registro.equipo);
    pos += 20;

    raf.seek(pos);
    raf.writeInt(registro.puntos);
    pos += 4;
}
    
answered by 08.01.2016 / 06:42
source
2

Since I do not know if you can use Arrays sort nor if you can implement Comparator<Comparable[]> to order array, I show it to you in another way:

    raf = new RandomAccessFile("Partides.dat", "rw");

    int registros = (raf.length()/48); //(int)

    //Empleamos dos array para ordenar y otro como apoyo para este fin
    int[] tempArrayData = new int[registros];
    int[] tempArrayPos  = new int[registros];

    int count = 0;

    for (long i = 44; i < raf.length() -4; i = i+48){

     raf.seek(i);
     int valorI = raf.readInt();

     tempArrayData[count] = valorI;
     tempArrayPos[count]  = i;

     count ++;
    }

    //en este punto es donde ordenamos los arrays   

    int a       = 0;
    int tmpData = 0;
    int tmpPos  = 0;
    boolean swa = true;

    while (swa) {

        swa = false;
        a++;

        for (int i = 0; i < tempArrayData.length - a; i++) {
            if (tempArrayData[i] > tempArrayData[i + 1]) {

                tmpData              = tempArrayData[i];
                tempArrayData[i]     = tempArrayData[i + 1];
                tempArrayData[i + 1] = tmpData;

                tempPos             = tempArrayPos[i];
                tempArrayPos[i]     = tempArrayPos[i + 1];
                tempArrayPos[i + 1] = tmpPos;

                swa = true;
            }
        }
    }
    //el array tempArrayPos contiene las posiciones ordenadas con respecto a los registros de menor a mayor, si el registro 4 es el de menor puntuacion estara en la posicion 0 del array
    //el array tempArrayData contiene las puntuaciones ordenadas como las anteriores 

    //en este punto, la pregunta que me surje es si usted tiene que guardar las puntuaciones ordenadas con sus ID ect asociadas en un nuevo archivo.dat,
    //o en el .dat existente,
    //o basta con que en este punto se muestren ordenadas con un println por ejemplo.

    //Muestra
    for (int a = tempArrayPos.length(); a > -1; a--){ 

        raf.seek((tempArrayPos[a]) - 44);
        System.out.println(raf.readInt()); 

        raf.seek((tempArrayPos[a]) - 40);
        System.out.println(raf.readUTF());

        raf.seek((tempArrayPos[a]) - 20);
        System.out.println(raf.readUTF());

        raf.seek(tempArrayPos[a]);
        System.out.println(raf.readInt());
    }
    //crea un nuevo dat
    RandomAccessFile rafNew = new RandomAccessFile("PartidesOrdenades.dat", "rw");
    int posNew = 0;   

    for (int a = tempArrayPos.length(); a > -1; a--){ 

    rafNew.seek(posNew);
    raf.seek((tempArrayPos[a]) - 44);

    rafNew.writeInt(raf.readInt());
    posNew += 4;
    //
    rafNew.seek(posNew);
    raf.seek((tempArrayPos[a]) - 40);

    rafNew.writeUTF(raf.readUTF());
    posNew += 20;
    //
    rafNew.seek(posNew);
    raf.seek((tempArrayPos[a]) - 20);

    rafNew.writeUTF(raf.readUTF());
    posNew += 20;
    //
    rafNew.seek(posNew);
    raf.seek(tempArrayPos[a]);

    rafNew.writeInt(raf.readInt());
    posNew += 4;
    }

    rafNew.close();
raf.close();

As I commented this code has not been compiled, if it works without failures I do not rule it out, but it would be strange, even so you can take it as a pseudo code, on the other hand you can read some of the doubts in the comments within the code, I hope it will help or at least help you.

    
answered by 08.01.2016 в 04:41