Escrever em arquivos, sem apagar o seu conteudo - Java

3 respostas Resolvido
filejava
C

Bom pessoal, quero saber como posso escrever em um arquivo sem apagar o que tem dentro dele. Estudei um pouco e vi algumas classes que trabalha com arquivos, podem me dizer se as formar de criar e ler arquivos abaixo eh correta? Qual voces recomendam?

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();
		}
	}

Esse codigo sempre sobrescreve o conteudo do arquivo. Grato.

3 Respostas

S
Solucao aceita

Utilize dessa forma: FileWriter x = new FileWriter(“teste.txt”,true)
Assim ele vai escrever no final do arquivo

try{
try (FileWriter x = new FileWriter("teste.txt",true)) {
    String gravaTeste = "Jesus is Perfect.\r\n";
            x.write(gravaTeste);
        }
    }  
    catch(IOException e){  
        System.out.println("Error: " + e.getMessage());
    }
C

Brigadão man, ajudou.

E

Amigo, criei uma conta em 2020 só para te agradecer kkkkkkkkkkk Me ajudou no trabalho da facul vlw ai

Criado 24 de novembro de 2016
Ultima resposta 30 de jun. de 2020
Respostas 3
Participantes 3