Search code examples
javafilewriter

Overwrite existing file in Java


I have the following code that writes a text file and saves the numbers from the user input.

for (contador = 0; contador < numeros; contador++){
                array[contador]= Integer.parseInt (JOptionPane.showInputDialog("Ingresa " + numeros + " números")); try{
                    File archivo = new File ("lista de numeros.txt");
                    FileWriter fr = new FileWriter (archivo,true);
                    fr.write(Integer.toString(array[contador]));
                    fr.write("\r\n");
                    fr.close();
                }catch(Exception e){
                    System.out.println("Error al escribir");
                }

What I want to do is to overwrite the file once is created not to append, however, if I change to false, it doesn't work because only saves the last number from user input. Is there another way to overwrite the file? Or is there something that I am missing?


Solution

  • You would want something along the lines of the code below. File/FileWriter declaration outside the try, initialization inside the try and close in the finally.

    File archivo = null;
    FileWriter fr = null;
    try {
        archivo = new File("lista de numeros.txt");
        fr = new FileWriter(archivo, true);
        for (contador = 0; contador < numeros; contador++) {
            array[contador] = Integer.parseInt(JOptionPane.showInputDialog("Ingresa " + numeros + " números"));
            fr.write(Integer.toString(array[contador]));
            fr.write("\r\n");
        } 
    } catch (Exception e) {
      System.out.println("Error al escribir");
    } finally {
      fr.close();
    }