Salvar uma String em um arquivo txt, com percistencia! Alguem pode me ajudar?[RESOLVIDO]

Estou fazendo uma agenda telefonia, mas não estou conseguindo salvar com percistencia em arquivo txt. Alguem poderia me ajudar?

Este é meu codigo que uso para salvar o arquivo

[code]private static void gravarEmArquivoTXT(Collection cCadastrar) throws IOException {

	BufferedWriter fr = new BufferedWriter(new FileWriter("C:\Gravacao_Arquivo.txt"));

	for (Iterator<Cadastrar> iterator = cCadastrar.iterator(); iterator.hasNext();){
		Cadastrar salva = (Cadastrar) iterator.next();

		 fr.write(salva.getNome()+";");
		 fr.write(salva.getTelefone()+";");
		
		 fr.newLine();
}
	        fr.close();[/code]

Obrigado!

experimenta colocar no code

[code]

fr.flush();// salva
fr.close();[/code]

[b]por que todo arquivo que abre… tem que fechar(salvando) o flush faz isso.

experimenta qualquer coisa posta resposta ai.

[]'s[/b]

Obrigado pela dica mais naum funcionou e ainda deu este erro.

h - ghjava.io.IOException: Stream closed
at java.io.BufferedWriter.ensureOpen(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)

at java.io.BufferedWriter.flush(Unknown Source)
at br.facet.si.paradigmas.telas.CadastroNome.gravarEmArquivoTXT(CadastroNome.java:177)
at br.facet.si.paradigmas.telas.CadastroNome.access$0(CadastroNome.java:165)
at br.facet.si.paradigmas.telas.CadastroNome$2.actionPerformed(CadastroNome.java:140)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

@

Tente algo assim:

private void geraArquivo(String conteudo) {
		try {
			FileWriter writer = new FileWriter(new File("C:/pnp.txt"));  
			PrintWriter saida = new PrintWriter(writer);
			saida.print(conteudo);
			saida.close();  
			writer.close();
			System.out.println("Arquivo criado com sucesso!");
		} catch (Exception e) {
			e.printStackTrace();
		}

}

O flush deve ser realizado logo antes de fechar o arquivo. :stuck_out_tongue:

O codigo deve ser:

fr.flush();
fr.close(); 

e não

fr.close(); 
fr.flush();

basta tomar cuidado, e dar uma olhada no javadoc por exemplo.

[code]
private static void gravarEmArquivoTXT(Cadastrar c) throws IOException {

	BufferedWriter fr = new BufferedWriter(new FileWriter("C:\Aluno.txt",true));//Abre arquivo para escrita
        
		 fr.write(c.getNome()+";");//escreve a matricula do aluno no arquivo
		 fr.write(c.getTelefone()+";");//escreve o nome do aluno no arquivo
                     fr.newLine();//passa para a proxima linha
                     fr.flush();
	         fr.close();

} [/code]

o que foi alterado foi nessa linha:

BufferedWriter fr = new BufferedWriter(new FileWriter("C:\Aluno.txt",true));

Percebam que eu coloquei um true depois do “destino do arquivo” na documentação do FileWriter tem alguns métodos 2 só pra entenderem o erro:

 public FileWriter(String fileName) {} ;

[b]nesse método ele vai sempre apontar no começo do arquivo e começar gravar.

e tem o método: [/b]

 public FileWriter (String fileName, boolean append) {}

[b]se tu passa o parametro boolean true… o método vai verificar onde foi parado a escrita no arquivo. e continuar daquele ponto.

espero que tenha sido claro.

[]'s[/b]

brigadão ajudou muito, valeu!!