add to JAVA text file

Asked

Viewed 88 times

0

in my code I wanted to add in the file but I’m not getting it, it always erases 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);

    }

}

1 answer

1


Hello.

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

Constructs a Filewriter Object Given a File Object. If the Second argument is true, then bytes will be Written to the end of the file rather than the Beginning.

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

FileWriter gravador = new FileWriter("arquivo.txt", true);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.