add in the JAVA Text file

0

In my code I wanted to add to the file but I can not, it always deletes the content from before.

package classejava;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import jdk.internal.jfr.events.FileWriteEvent;

public class escritor {

    public static void entraVetor(float[] vetor, int n) {
        Scanner entrada = new Scanner(System.in);
        for (int i = 0; i < n; i++) {
            vetor[i] = entrada.nextFloat();

        }
    }

    public static void gravaArquivo(float[] vet, int n) throws IOException {

        FileWriter gravador = new FileWriter("arquivo.txt");
        BufferedWriter buffer = new BufferedWriter(gravador);
        for (int i = 0; i < n; i++) {
            buffer.write(" " + vet[i]);
            buffer.flush();
        }

    }

    public static void main(String[] args) throws IOException {
        Scanner entrada;
        entrada = new Scanner(System.in);
        float[] vet;
        int n;
        n = entrada.nextInt();
        vet = new float[n];
        entraVetor(vet, n);
        gravaArquivo(vet, n);

    }

}
    
asked by anonymous 16.05.2017 / 01:19

1 answer

1

Hello.

The object FileWriter has a two-argument constructor being FileWriter(File file, boolean append) where:

  

Constructs a FileWriter object given to a File object. If the second argument is true, then it will be written to the end of the file rather than the beginning.

That is, if you want to add content to the end of your file, you must pass true to the append parameter as follows:

FileWriter gravador = new FileWriter("arquivo.txt", true);
    
16.05.2017 / 02:48