How can I make a file with the structure of a stack? [closed]

0

I have a stack of 3 elements and when closing the program, this program has to write a file emptying the remaining elements of a stack and then read them from the file and add them to the stack in the same way they were inserted.

That is, if the elements are on the stack:

3
2
1

The file has to be saved in that order, but I do not know how this can be done if the file is extracted from the stack and added to the file. Is there any way for you to save the data in the same format as a stack?

    
asked by Marco Leslie 11.10.2017 в 22:14
source

1 answer

1

As Pablo Lozano said, you need an auxiliary battery where you have to pass the data from the original so as not to alter the order of the data.

Since you did not specify the language in which you need to do this, I'll give you an example in java.

Basically the program passes the data of the original stack (without altering its order to a .dat file You can modify it to your liking, where before passing the data to the files, you can add / subtract or make any other operation you want.)

public class PasoPilaAlArchivo {

public static void main(String[] args) {
    //declaro pila
    Stack <String> pilaOriginal = new Stack<String>();
    pilaOriginal.push("1");
    pilaOriginal.push("2");
    pilaOriginal.push("3");


    //declaro la pila auxiliar para no alterar el orden de los datos apilados
    Stack <String> pilaAux = new Stack<String>();

    //paso los datos de pila original al auxiliar
    while(!pilaOriginal.isEmpty()){
        pilaAux.push(pilaOriginal.pop());
    }

    // defino la ruta
    String ruta = "...definir ruta del archivo";
    // declaro el fichero (con la ruta y el nombre)
    File fichero = new File(ruta, "numerosPila.dat");

    // creo el flujo de salida hacia el fichero, si el fichero es NULL,
    // genera una IOexcepcion
    try (FileOutputStream flujoSalida = new FileOutputStream(fichero)) {
        System.out.println("Escribiendo fichero...");
        // el ciclo que llena el buffer con los numeros, si el buffer se
        // queda sin memoria,genera la
        // excepcion ArrayIndexOutOfBoundsException

        // paso el contenido del buffer al archivo a traves del flujo de
        // salida
        while(!pilaAux.isEmpty()){
            byte[] datos = pilaAux.pop().getBytes();
            flujoSalida.write(datos);
        }

        // cierro el flujo de salida
        flujoSalida.close();
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (ArrayIndexOutOfBoundsException e2) {
        System.out.println("ERROR: El buffer no tiene mas memoria, modificar su tamaño.");
    }

}

}

    
answered by 11.10.2017 / 23:00
source