Write in files without deleting your content

-1

How can I write to a file without deleting what's inside it? I'm using the classes below.

public void criarArquivos() throws IOException{

    /*1 forma*/
    FileWriter arqTeste = new FileWriter("teste.txt");
    PrintWriter gravaTeste = new PrintWriter(arqTeste);
    gravaTeste.println("Jesus is Perfect.");
    arqTeste.close();

    /*2 forma*/
    Formatter arquivo = new Formatter("teste2.txt");
    arquivo.format("Jesus is love, but Justice too.");
    arquivo.close();
}

public void lerArquivos() throws IOException{
    /*1 forma*/
    FileReader obter = new FileReader("teste.txt");
    BufferedReader receber = new BufferedReader(obter); //pq tem advertencia?

    String frase = receber.readLine();
    while(frase != null) {
        System.out.println(frase);
        frase = receber.readLine();
    }

    /*2 forma*/
    FileInputStream arq = new FileInputStream("teste2.txt");
    InputStreamReader ler = new InputStreamReader(arq);
    BufferedReader leitura = new BufferedReader(ler);   //pq tem advertencia?

    String linha = leitura.readLine();
    while(linha != null) {
        System.out.println(linha);
        linha = leitura.readLine();
    }
}
    
asked by anonymous 24.11.2016 / 14:54

3 answers

2

You should instantiate FileWriter with the parameter true , see :

try(FileWriter fw = new FileWriter("outfilename", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("texto");
    out.println("outro texto");
} catch (IOException e) {
    // exceção
}

This will cause the file to open in append mode, that is, to add data and not overwrite it.

Using a buffer to write to the file is most appropriate since disk access operations are slower.

    
24.11.2016 / 15:12
1

One of the options is to create a method where you will pass the file path and the text that will be applied:

private void escrever(String caminho, String conteudo) throws IOException {
  Path arquivo;

  arquivo = Paths.get(caminho);
  Files.write(arquivo, conteudo.getBytes(), StandardOpenOption.APPEND);
}

How to append text to an existing file in Java

    
24.11.2016 / 15:16
0

One option is to use the Files class. It would look something like:

    try {
        Files.write(Paths.get("C:/arquivo.txt"), "NOVO TEXTO".getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
        e.printStackTrace();
    } 

The write method expects three parameters:

  • path - the path of the file
  • bytes - byte array with bytes to write
  • options - option that specifies how the file is opened. Append is suggestive which will add, not overwrite.
24.11.2016 / 15:15