DataOutputStream and keyboard reading with Scanner

2
  

The program runs but ends without anything being shown   screen. Does anyone know why?

public static void mostrarProductos() {

        DataInputStream dataInputStream = null;

        try {
            dataInputStream = new DataInputStream(new FileInputStream("Lista_compra.dat"));

            while (true) {
                int i = dataInputStream.readInt();
                String s = dataInputStream.readUTF();
                System.out.println("Producto " + i + " : " + s);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            // Esta excepción es para ver que hemos llegado el final del fichero
        } catch (EOFException e) {

            System.out.println("Hemos terminado de leer nuestra lista de compra");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

public static void anyadirProducto() {

        String compra = "";

        DataOutputStream dataOutputStream = null;
        Scanner sc = new Scanner(System.in);
        System.out.println("Inserta producto: ");
        compra = sc.nextLine();
        try {
            dataOutputStream = new DataOutputStream(new FileOutputStream("Lista_compra.dat"));

            dataOutputStream.writeUTF(compra);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
  

Output by console:

Elija una opción: 
1.Añadir producto
2.Mostrar productos
3.Salir

Inserta opción:  1 Inserta producto:  pan Elija una opción: 
1.Añadir producto
2.Mostrar productos
3.Salir

Inserta opción:  2 Hemos terminado de leer nuestra lista de compra Elija una opción: 
1.Añadir producto
2.Mostrar productos
3.Salir

Inserta opción:
    
asked by Jose 23.09.2016 в 12:18
source

2 answers

1
  

Well, I auto answered after giving it a few laps, this time   using a try with resources (autoclosable) to make the code more   simple, I hope someone serves you.   It works perfectly.

public class Crud {

    // Este método nos va a permitir sobreescribir un archivo existente o no, el
    // boolean
    // FileOutputStream(File file, boolean append)

    public static void addProduct() throws IOException {

        Scanner sc = new Scanner(System.in);

        // Crear la salida
        try (FileOutputStream fos = new FileOutputStream(new File("compra.data"), true);
                DataOutputStream dos = new DataOutputStream(fos))

        {
            System.out.println("Inserte alimento: ");
            String compra = sc.nextLine();

            dos.writeUTF(compra);
            dos.flush();

        }

    }

    public static void showProduct() throws IOException {

        try (FileInputStream fis = new FileInputStream(new File("compra.data"));
                DataInputStream dis = new DataInputStream(fis))

        {
            while (dis.available() > 0) {
                // read character
                String c = dis.readUTF();

                // print
                System.out.print(c);

            }

        }
    }
}
    
answered by 27.09.2016 / 12:23
source
6

Problem:

You have an infinite loop, which prevents the code that is after the infinite loop from running:

while (true) {
    int i = dataInputStream.readInt();
    String s = dataInputStream.readUTF();
    System.out.println("Producto " + i + " : " + s);
}

while(true) will never end, because true is always true .

Solution:

You need to check that you have finished reading the file, you can do it like this:

while(dataInputStream.available()>0)
    int i = dataInputStream.readInt();
    String s = dataInputStream.readUTF();
    System.out.println("Producto " + i + " : " + s);
}

Extra:

That code should work, but it can still be improved. Normally it is not optimal to create variables within while , because you create them many times, and that consumes resources (Memory, CPU ...), this would be better:

int i=0;
String s=null;
while(dataInputStream.available()>0)
    i = dataInputStream.readInt();
    s = dataInputStream.readUTF();
    System.out.println("Producto " + i + " : " + s);
}

Edit / Update: I did not realize before, you say that FileNotFoundException will skip when the whole file has been read, this is not exactly like that.

FileNotFoundException will skip when the program can not find the file. The bug may be here, make sure you're accessing the file, if you skip this exception it may mean the file was not found.

I've also seen that you use EOFException to "force" the while loop to finish. This can work, yes, but it is not advisable, I recommend using while(dataInputStream.available()>0) .

    
answered by 23.09.2016 в 13:28