Iniciante tentando Gravar Arquivo

1 resposta
mota

Pessoal, eu queria saber pq esse código n funciona. O objetivo é gravar um arquivo .txt. Mas não estou conseguindo.
Por favor, preciso de ajuda.

Código para Gravar arquivo

package testeArquivo; import javax.swing.*; import java.io.*; public class GravaArquivo extends JFrame { String nameFile = "testeArquivo/dados.txt"; ObjectOutputStream file; Registro r; int codigos[] = {1, 2, 3, 4, 5}; String nomes[] = {"Carlos", "Maria", "Ana", "Silvia", "Marta"}; double valores[] = {3.5, 2.3, 1.7, 5.8, 9.0}; public GravaArquivo() { openW(); try { for (int i = 0; i < codigos.length; i++) { r = new Registro(codigos[i], nomes[i], valores[i]); file.writeObject(r); } } catch(Exception e) {} finally { closeW(); } } void openW() { try { file = new ObjectOutputStream(new FileOutputStream(nameFile)); } catch(Exception e) { } } void closeW() { try { file.close(); }catch(Exception e) { } } public static void main(String[] args) { GravaArquivo a = new GravaArquivo(); a.setDefaultCloseOperation(EXIT_ON_CLOSE); } }

Código para Ler Arquivo

package testeArquivo; import javax.swing.*; import java.io.*; public class LeArquivo extends JFrame { String nameFile = "testeArquivo/dados.txt"; ObjectInputStream file; Registro registro; public LeArquivo() { openR(); String str = ""; try { while(true) { registro = (Registro)file.readObject(); str += "Código: "+registro.getCodigo()+ " Nome: "+registro.getNome()+ " Valor: "+registro.getValor()+"\n"; } } catch (EOFException e) { //fim de arquivo closeR(); return; } catch (Exception ee) { } finally { JOptionPane.showMessageDialog(null, str); } } void openR() { try { file = new ObjectInputStream(new FileInputStream(nameFile)); } catch(Exception e) { } } void closeR() { try { file.close(); }catch(Exception e) { } } public static void main(String[] args) { LeArquivo la = new LeArquivo(); la.setDefaultCloseOperation(EXIT_ON_CLOSE); } }

Código da classe Registro

package testeArquivo; import java.io.*; public class Registro implements Serializable { int codigo; String nome; double valor; public Registro() {} public Registro(int codigo, String nome, double valor) { this.codigo = codigo; this.nome = nome; this.valor = valor; } int getCodigo() { return codigo; } String getNome() { return nome; } double getValor() { return valor; } void setCodigo(int codigo) { this.codigo = codigo; } void setNome(String nome) { this.nome = nome; } void setValor(double valor) { this.valor = valor; } }

Por favor, preciso de ajuda. Quem fez o código foi um primo meu. O código está correto?

1 Resposta

UMC

Olha aqui!:

Manipulando TXT:
http://umcastec.blogspot.com/2010/04/lendo-um-arquivo-usando-bufferedreader.html
http://umcastec.blogspot.com/2010/04/escrevendo-em-um-arquivo-usando.html

vlw
abs

Criado 13 de abril de 2010
Ultima resposta 13 de abr. de 2010
Respostas 1
Participantes 2