Gravar arquivo txt

3 respostas
B
Pessoal tenho q fazer um programinha q grave em arquivos txt para amanha, tenho que gravar produtos e depois mostra. Fiz um programa para testar, para gravar, so q ele ta sobrescrevendo. alguem poderia me ajudar
package br.com.SistemaVenda.trabalho;

import javax.swing.JOptionPane;

public class Cadastro {

 
	public static void main(String[] args) {
		
		
		
		Cliente cliente = new Cliente();
		
		String nome = JOptionPane.showInputDialog("Informe o nome do cliente");
		cliente.setNome(nome);
		
		String email = JOptionPane.showInputDialog("Informe email do cliente");
		cliente.setEmail(email);
		
		int idade = Integer.parseInt(JOptionPane.showInputDialog("Informe a idade cliente"));
		cliente.setIdade(idade);
		
		
		JOptionPane.showConfirmDialog(null, "Você deseja gravar " +cliente.salvar());
		
	}

}
package br.com.SistemaVenda.trabalho;

import java.io.File;
import java.io.FileWriter;


public class Cliente {

	private String nome;
	private String email;
	private int idade;
	
	
	public String getNome() {
		return nome;
	} 
	
	public void setNome(String nome) {
		this.nome = nome;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public int getIdade() {
		return idade;
	}

	public void setIdade(int idade) {
		this.idade = idade;
	}


	public String salvar(){
		File fl = new File("C:\\dados\\cliente.txt");
		
		
		//se o arquivo nao existe
		if(!fl.exists()){
			try {
				fl.createNewFile();
				FileWriter writer = new FileWriter(fl);
				
				writer.write(this.nome + " - " + this.email + " - " + this.idade);
				writer.flush();
				writer.close();
				
			} catch (Exception ex) {
				return "Erro no Sistema . Msg: " +ex.getMessage();
				
			}
		}
		return "Sucesso ao Cadastrar";
}

3 Respostas

CristianPalmaSola10

ele sobrescreve por causa disso

if(!fl.exists()){  
            try {  
                -->fl.createNewFile();<---
                FileWriter writer = new FileWriter(fl);  
                  
                writer.write(this.nome + " - " + this.email + " - " + this.idade);  
                writer.flush();  
                writer.close();  
                  
            } catch (Exception ex) {  
                return "Erro no Sistema . Msg: " +ex.getMessage();  
                  
            }  
        }  
        return "Sucesso ao Cadastrar";
Demys_Cota

Se não der certo tente isto

if(!fl.exists()){

try {

–>fl.createNewFile();<—

FileWriter writer = new FileWriter(fl,true);
writer.append(this.nome + " - " + this.email + " - " + this.idade);    
            writer.flush();    
            writer.close();    
                
        } catch (Exception ex) {    
            return "Erro no Sistema . Msg: " +ex.getMessage();    
                
        }    
    }    
    return "Sucesso ao Cadastrar";
Demys_Cota

Sempre que criar o Filewriter, utilize o construtor com dois argumento, FileWriter(nome arq, boolean append) = o segundo argumento pergunta se é para adicionar ou sobrescrever.

Criado 4 de abril de 2013
Ultima resposta 4 de abr. de 2013
Respostas 3
Participantes 3